How do I convert a JSONObject to class object?

后端 未结 5 1199
南旧
南旧 2020-12-05 18:19

I need to convert a JSONObject to a Location object using gson libraries for an android project of mine. I\'m not sure on how to do this. Can anyone help me with this. Thank

相关标签:
5条回答
  • 2020-12-05 18:38

    You can use moshi! moshi is very great when STRING JSON to Object! Especialy if you get jsonObject when request to server (which is very boilerplate to convert to object each)

    More bug fixing and more clean! Moshi has built-in support for reading and writing Java’s core data types:

    • Primitives (int, float, char...) and their boxed counterparts (Integer, Float, Character...)
    • Arrays, Collections, Lists, Sets, and Maps Strings Enums

    Moshi

    0 讨论(0)
  • 2020-12-05 18:40

    if you still want to use org.json.JSONObject:

    org.json.JSONObject o;
    ObjectMapper m = new ObjectMapper();
    MyClass myClass = m.readValue(o.toString(), MyClass.class);
    
    0 讨论(0)
  • 2020-12-05 18:40

    use com.google.gson.JsonObject & JsonArray instead of org.json.*

    like this :

    Gson gson = new Gson();
    Type typeOfT = new TypeToken<List<Location.class>>(){}.getType();
    JsonParser parser = new JsonParser();
    JsonObject jo = (JsonObject) parser.parse(jsonStr);
    JsonArray ja = jo.getAsJsonArray("memberName");
    list = gson.fromJson(ja, typeOfT);
    
    0 讨论(0)
  • 2020-12-05 18:56

    Here's a tutorial for GSON - I think it should help bolster your understanding. Essentially the parsing is done like this:

    String mJsonString = "...";
    JsonParser parser = new JsonParser(); 
    JsonElement mJson =  parser.parse(mJsonString);
    Gson gson = new Gson();
    MyDataObject object = gson.fromJson(mJson, MyDataObject.class);
    
    0 讨论(0)
  • 2020-12-05 19:01

    For kotlin

     val objType = object : TypeToken<MyClass>() {
    
        }.getType()
        var myclassObj = gson.fromJson(value,objType) 
    

    or

     val objectResponse = Gson().fromJson(Gson().toJson(resp), MyClass::class.java)
    
    0 讨论(0)
提交回复
热议问题