How to remove special characters from JSON stream, so that I can use gson API to convert JSON objects to JAVA objects?

前端 未结 3 715
生来不讨喜
生来不讨喜 2021-01-19 03:43

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 t

相关标签:
3条回答
  • 2021-01-19 04:13

    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));
    
    0 讨论(0)
  • 2021-01-19 04:14

    The easiest way would be to turn the stream into a string, use a regex or something to replace the undesired characters, then invoke gson to convert the corrected string into the Java object you want.

    0 讨论(0)
  • 2021-01-19 04:24

    As I understand it, your object's JSON representation contains a value such as "0%" (which is officially a String from JSON's point of view). This is certainly valid JSON, and GSON should accept it...if you were deserializing it to something that was designed to contain a String.

    My guess is that you actually want the "0" to be deserialized into a numeric type. In this case, you can't rely on GSON to do what you want automatically, and you will need to write a custom deserializer.

    The example in the link above shows how one might do this for a DateTime object:

    private class DateTimeDeserializer implements JsonDeserializer<DateTime> {
      public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
          throws JsonParseException {
        return new DateTime(json.getAsJsonPrimitive().getAsString());
      }
    }
    

    In your case, you will still need to do a getAsString(), but instead of passing it to the DateTime constructor, you would want to apply your own transformations (strip the "%", parse the numeric part, etc) and return the appropriate data type that corresponds to your object.

    0 讨论(0)
提交回复
热议问题