【发布时间】:2016-02-08 11:55:56
【问题描述】:
我正在尝试使用 GSON api 将一些字符串数据格式化为 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 注释中指定的方式打印键名。
谢谢!
【问题讨论】: