Converting json string to java object?

前端 未结 3 1681
情书的邮戳
情书的邮戳 2020-11-28 08:58

I have been looking around for examples related to converting JSON strings to Java object but haven\'t found any good examples. The one I found was really basic once and not

3条回答
  •  半阙折子戏
    2020-11-28 09:11

    EDIT: You need your java Data class to be an exact model of the JSON. So your

    {"data":{"translations":[{"translatedText":"Bonjour tout le monde"}]}} 
    

    becomes:

    class DataWrapper {
        public Data data;
    
        public static DataWrapper fromJson(String s) {
            return new Gson().fromJson(s, DataWrapper.class);
        }
        public String toString() {
            return new Gson().toJson(this);
        }
    }
    class Data {
        public List translations;
    }
    class Translation { 
        public String translatedText;
    }
    

    As the object model gets more complicated the org.json style code veers towards unreadable whereas the gson/jackson style object mapping is still just plain java objects.

提交回复
热议问题