String unknown to JSON in Java

后端 未结 1 1975
萌比男神i
萌比男神i 2021-01-28 09:42

I\'ve got a string from an URL which I know is formatted as a JSON but I don\'t know the field that can change and the size. I try to parse it into a JSON Object to be able to i

1条回答
  •  无人共我
    2021-01-28 10:34

    My best experience with mapping is com.fasterxml.jackson

    use to make a Json String from your class (whatever the subclasses, as long as all have appropriate getters and setters, and an empty (public) constructor)

    public String toJson() {
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        StringWriter stringEmp = new StringWriter();
        try {
            objectMapper.writeValue(stringEmp, this);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringEmp.toString();
    }
    

    use

    public static ThisClass initFromJson(final String json) {
        final ObjectMapper mapper = new ObjectMapper();
        ThisClass item;
        try {
            item = mapper.readValue(json, ThisClass.class);
        } catch (IOException e) {
            return null;
        }
    
        return item;
    }
    

    to load the class from the json strings

    If you have a Json object and don't have the Java fields for it, you might want to try http://timboudreau.com/blog/json/read to generate the Java code.

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