Converting json string to java object?

前端 未结 3 1580
情书的邮戳
情书的邮戳 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<Translation> 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.

    0 讨论(0)
  • 2020-11-28 09:16

    check this out Converting JSON to Java , i guess you can define a class as the object and pass that along. So, create some class and pass it along.

    Data obj = gson.fromJson(json, Data.class);

    class Data{
      public List<Data> getTranslation(){
         return translations;
      }
    }
    

    Try out something like that. You may need to experiment a little.

    0 讨论(0)
  • 2020-11-28 09:27

    I usually like to use the plain org.json library

    Use it as:

     // make sure the quotes are escaped
    String str = "{\"data\":{\"translations\":[{\"translatedText\":\"Bonjour tout le monde\"}]}}";
     // the object data is inside a "global" JSONObject
    data = new JSONObject(str).getJSONObject("data");
    // get a JSONArray from inside an object
    JSONArray translations = data.getJSONArray("translations");
    // get the first JSONObject from the array
    JSONObject text = translations.getJSONObject(0);
    // get the String contained in the object -> logs Bonjour tout le monde
    Log.d("***>Text", text.getString("translatedText"));
    

    Maybe so much code is less clear than what I would have liked. This is the function as I would do it:

    public String getTranslation(String json){  
      JSONObject data = new JSONObject(json).getJSONObject("data");
      return data.getJSONArray("translations").getJSONObject(0).getString("translatedText");
    }
    
    0 讨论(0)
提交回复
热议问题