我正在使用一个don服务,不幸的是我无法控制它,有一个叫做价格的元素可以有两种类型的值,它可以是双精度的:
price: 263.12或具有特定格式的字符串:
price: "263.12;Y"在第二种情况下,;N表示价格可以修改(即:可以添加折扣),我试图说服服务的开发人员修改响应,并以单独的值发送Y或N(取决于具体情况)(折扣:"Y“|”N:“),但他们表示目前不会这样做。
在我为这种情况声明的POJO中,我有以下情况:
private float precio;
public void setPrice(String value){
if(value.indexOf(";") == -1){
price = Float.parseFloat(value);
} else {
String[] p = value.split(";");
price = Float.parseFloat(p[0]);
}
}
public float getPrice(){return price;}但不幸的是,使用:
Product obj = new Gson().fromJson(response, Product.class); 实际上从来不调用setter,在价格被设置为合适的双精度值的情况下,它工作得很好,但是在我收到字符串的地方它就崩溃了,关于如何处理这种情况的任何建议,最坏的情况我可以创建第二个POJO并尝试/捕获对象创建,但是应该有一个更好的想法,搜索到目前为止没有结果。
发布于 2013-06-18 04:20:17
您可以实现一个覆盖默认序列化的TypeAdapter。您必须为某个类注册该TypeAdapter ...
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Product.class, new ProductAdapter());
Gson gson = builder.create();..。这样,任何类型为Product的成员..。
String jsonString = gson.toJson(somethingThatContainsProducts); ..。将由TypeAdapter处理
public class ProductAdapter extends TypeAdapter<Product> {
public Product read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
String json = reader.nextString();
// convert String to product ... assuming Product has a
// constructor that creates an instance from a String
return new Product(json);
}
public void write(JsonWriter writer, Product value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
// convert Product to String .... assuming Product has a method getAsString()
String json = value.getAsString();
writer.value(json);
}
} 查看Google GSON documentation了解更多信息。
希望这能帮到你。干杯!
发布于 2013-06-18 21:30:03
您可以编写一个TypeAdapter或JsonDeserializer。
你也可以依赖于这样一个事实,Gson将为你处理类型,而反过来处理你的类型:
class Pojo { String price; }
...
String json = "{\"price\":1234.5}";
Pojo p = new Gson().fromJson(json, Pojo.class);
System.out.println(p.price);产生:
1234.5
当您想要将price作为double访问/获取时,请在getter中对其进行适当的转换。
https://stackoverflow.com/questions/17154629
复制相似问题