如何从JSON流中删除特殊字符,以便我可以使用gson API将JSON对象转换为JAVA对象? [英] How to remove special characters from JSON stream, so that I can use gson API to convert JSON objects to JAVA objects?

查看:127
本文介绍了如何从JSON流中删除特殊字符,以便我可以使用gson API将JSON对象转换为JAVA对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使用Google gson API将JSON对象序列化为java对象。
我需要从序列化中删除这个流中的特殊字符。
我该如何做到这一点?



这是我从请求中获得的JSON对象:



{color:北极白,imageUrl:http://www.xyz.com/images/z/1/7/8/8/2/1/1788212-p-DETAILED.jpg styleId: 1788212, originalPrice: $ 64.95, 价格: $ 64.95, PRODUCTURL: http://www.xyz.com/product/7515478/color/51609,然而,当我尝试使用Google的gson API将其反序列化为JAVA对象时,它需要没有任何特殊字符的JSON对象,因此它遇到'$'和'%'时会引发异常。如何在不影响其他json对象的情况下摆脱这些字符,即将json结果作为字符串获取。

解决方案

完美如预期。不需要从JSON流中移除这些特殊字符以将其转换为Java对象。



请看下面的示例代码:

  BufferedReader阅读器= new BufferedReader(new FileReader(new File(json.txt))); 
MyJSONObject data = new Gson()。fromJson(reader,MyJSONObject.class);
System.out.println(new GsonBuilder()。setPrettyPrinting()。create()。toJson(data));

class MyJSONObject {
private String color;
private String imageUrl;
private String styleId;
private String originalPrice;
私人字符串价格;
private String productUrl;
私人字符串percentOff;
// getter& setter
}

输出:(由于受到StackOverflow的限制,我从输出中删除了URL网站)

  {
color:Arctic White,
styleId:1788212 ,
originalPrice:$ 64.95,
price:$ 64.95,
percentOff:0%
}






您可以使用 JsonDeserializer 按照您的需要对其进行反序列化。



我已经发布了一个示例代码。找到它这里






编辑



是使用 JsonDeserializer 的示例代码。



示例代码:

  BufferedReader reader = new BufferedReader(new FileReader(new File(resources / json29.txt))); 

class MyJSONObject {
private String color;
private String imageUrl;
private String styleId;
私人双原创价格;
私人双重价格;
private String productUrl;
private double percentOff;
// getter& setter
}

class MyJSONObjectDeserializer实现了JsonDeserializer< MyJSONObject> {
$ b $ @Override
public MyJSONObject deserialize(final JsonElement json,final Type typeOfT,$ b $ final JsonDeserializationContext context)throws JsonParseException {

JsonObject jsonObject = json .getAsJsonObject();

MyJSONObject myJSONObject = new MyJSONObject();
myJSONObject.setColor(jsonObject.get(color)。getAsString());
myJSONObject.setImageUrl(jsonObject.get(imageUrl)。getAsString());
myJSONObject.setStyleId(jsonObject.get(styleId)。getAsString());
myJSONObject.setProductUrl(jsonObject.get(productUrl)。getAsString());

尝试{
String price = jsonObject.get(price)。getAsString();
String originalPrice = jsonObject.get(originalPrice)。getAsString();
String percentOff = jsonObject.get(percentOff)。getAsString();

myJSONObject.setPrice(Double.valueOf(price.substring(1)));
myJSONObject.setOriginalPrice(Double.valueOf(originalPrice.substring(1)));
myJSONObject.setPercentOff(Double.valueOf(percentOff.substring(0,
percentOff.length() - 1)));

} catch(NumberFormatException e){
e.printStackTrace();
}

返回myJSONObject;


$ b $ MyJSONObject data = new GsonBuilder()
.registerTypeAdapter(MyJSONObject.class,new MyJSONObjectDeserializer())。create()
。 fromJson(reader,MyJSONObject.class);

System.out.println(new GsonBuilder()。setPrettyPrinting()。create()。toJson(data));


I am trying to use Google gson API to serialize JSON objects to java objects. I need to remove special characters from this stream for the serialization. How do I achieve this?

This is the JSON object I get from the request:

{"color":"Arctic White","imageUrl":"http://www.xyz.com/images/z/1/7/8/8/2/1/1788212-p-DETAILED.jpg","styleId":"1788212","originalPrice":"$64.95","price":"$64.95","productUrl":"http://www.xyz.com/product/7515478/color/51609","percentOff":"0%"}

However, when I try to use Google's gson API to deserialize it to JAVA object- it needs JSON object without any special characters and hence it throws an exception when it encounters '$' and '%'. How can I get rid of these characters without affecting rest of the json object i.e. json result obtained as a string.

解决方案

It works perfectly as expected. There is no need to remove these special characters from JSON stream to convert it into Java object.

Please have a look at below sample code:

BufferedReader reader = new BufferedReader(new FileReader(new File("json.txt")));
MyJSONObject data = new Gson().fromJson(reader, MyJSONObject.class);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));

class MyJSONObject {
    private String color;
    private String imageUrl;
    private String styleId;
    private String originalPrice;
    private String price;
    private String productUrl;
    private String percentOff;
    // getter & setter
}

output: (I have deleted URLs from the output due to constrain of StackOverflow site)

{
  "color": "Arctic White",
  "styleId": "1788212",
  "originalPrice": "$64.95",
  "price": "$64.95",
  "percentOff": "0%"
}


You can try with JsonDeserializer to deserializer it as per your need.

I have already posted a sample code on it. Find it HERE


EDIT

Here is the sample code using JsonDeserializer.

Sample code :

BufferedReader reader = new BufferedReader(new FileReader(new File("resources/json29.txt")));

class MyJSONObject {
    private String color;
    private String imageUrl;
    private String styleId;
    private double originalPrice;
    private double price;
    private String productUrl;
    private double percentOff;
    // getter & setter
}

class MyJSONObjectDeserializer implements JsonDeserializer<MyJSONObject> {

    @Override
    public MyJSONObject deserialize(final JsonElement json, final Type typeOfT,
            final JsonDeserializationContext context) throws JsonParseException {

        JsonObject jsonObject = json.getAsJsonObject();

        MyJSONObject myJSONObject = new MyJSONObject();
        myJSONObject.setColor(jsonObject.get("color").getAsString());
        myJSONObject.setImageUrl(jsonObject.get("imageUrl").getAsString());
        myJSONObject.setStyleId(jsonObject.get("styleId").getAsString());
        myJSONObject.setProductUrl(jsonObject.get("productUrl").getAsString());

        try {
            String price = jsonObject.get("price").getAsString();
            String originalPrice = jsonObject.get("originalPrice").getAsString();
            String percentOff = jsonObject.get("percentOff").getAsString();

            myJSONObject.setPrice(Double.valueOf(price.substring(1)));
            myJSONObject.setOriginalPrice(Double.valueOf(originalPrice.substring(1)));
            myJSONObject.setPercentOff(Double.valueOf(percentOff.substring(0,
                    percentOff.length() - 1)));

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        return myJSONObject;
    }
}

MyJSONObject data = new GsonBuilder()
        .registerTypeAdapter(MyJSONObject.class, new MyJSONObjectDeserializer()).create()
        .fromJson(reader, MyJSONObject.class);

System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));

这篇关于如何从JSON流中删除特殊字符,以便我可以使用gson API将JSON对象转换为JAVA对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆