MWoot February 2016

GSON not returning key name, only value (Java)

I'm trying to format some String data to JSON using the GSON api, as shown in my returnJson() method:

import com.google.gson.*;
import com.google.gson.annotations.SerializedName;

public class HUKD {
    @SerializedName("title")
    public String title;
    @SerializedName("Deal URL")    
    public String dealUrl;
    @SerializedName("Product URL")    
    public String productUrl;
    @SerializedName("Image URL")        
    public String imgUrl;
    @SerializedName("Description")        
    public String description; 
    @SerializedName("Temperature")        
    public String temperature;
    @SerializedName("EAN")
    public String ean;
    @SerializedName("Price")
    public String price;
    @SerializedName("Amazon Price")
    public String amazonPrice;
    @SerializedName("Price Difference")
    public String priceDifference;
    @SerializedName("Amazon URL")
    public String amazonUrl;

    public HUKD(String title, String dealUrl, String productUrl, String imgUrl, String description, String temperature, String ean, String price, String amazonPrice, String priceDifference, String amazonUrl) {
        this.title = title;
        this.dealUrl = dealUrl;
        this.productUrl = productUrl;
        this.imgUrl = imgUrl;
        this.description = description;
        this.temperature = temperature;
        this.ean = ean;
        this.price = price;
        this.amazonPrice = amazonPrice;
        this.priceDifference = priceDifference;
        this.amazonUrl = amazonUrl;
    }

public String returnJson(){
    System.out.println("********TESTING OBJECTS*************");
    String[] jsonBuilder = new String []{title, dealUrl, productUrl, imgUrl, description, temperature, ean, price, amazonPrice, priceDifference, amazonUrl};
    Gson gson = new GsonBuilder().setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
    String json = gson.toJson(jsonBuilder );
    return json;
}

However, GSON wi

Answers


glw February 2016

You are not serializing your object, but array of Strings so you see proper result of this serialization. If you want to serialize your object you must use something like this:

public String returnJson(){
    Gson gson = new GsonBuilder().setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
    String json = gson.toJson(this);
    return json;
}

Post Status

Asked in February 2016
Viewed 3,542 times
Voted 8
Answered 1 times

Search




Leave an answer