我正在尝试使用GSON api将一些String数据格式化为JSON,如我的returnJson()方法所示:
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;
}
但是,GSON只返回值,而不是键:
[
"Philips shm3560/10 on ear headphones £8.99 from Argos",
"http://www.hotukdeals.com/deals/philips-shm3560-10-headphones-8-99-from-argos-2390246?aui\u003d1063",
"http://www.hotukdeals.com/visit?m\u003d5\u0026q\u003d2390246",
"http://static.hotukdeals.com/images/threads/2390246_1.jpg",
"Argos cat no- 108/7390\nhttp://www.argos.co.uk/webapp/wcs/stores/servlet/SearchMobile?storeId\u003d10151\u0026catalogId\u003d25051\u0026langId\u003d110\u0026searchTerm\u003d108%2F7390",
"171°",
"8712581626211",
"£8.99",
"£12.59",
"Argos is cheaper than Amazon by £3.60",
"http://www.amazon.co.uk/Philips-SHM3560-10-Pc-headset-Shm3560/dp/B008FSE6EU%3FSubscriptionId%3DAKIAILN2TPM667MBMJAQ%26tag%3Dgithubcomthis-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB008FSE6EU"
]
我试图通过添加API文档here的“JSON字段命名支持”部分中建议的SerializedName注释来解决这个问题,但我仍然没有运气。理想情况下,我喜欢JSON格式如下:
"title":"Philips shm3560/10 on ear headphones £8.99 from Argos"
(依此类推......),即在字段声明中的@SerializedName注释中打印的键名称。
谢谢!
答案 0 :(得分:1)
您没有序列化您的对象,而是序列化数组,以便您看到此序列化的正确结果。如果要序列化对象,则必须使用以下内容:
public String returnJson(){
Gson gson = new GsonBuilder().setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
String json = gson.toJson(this);
return json;
}