27

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. Thanks in advance.

I have a code something like

JSONArray input = new JSONArray(extras.getString("loc_json"));

I wanted to convert the JSONObject taken from the JSONArray to a Location class object. I just wanted to know whether there is a function that does it directly.

Pardon me if I framed the question in a wrong way. Since I haven't got the direct function, I did it in this way.

 loc_temp = (Location) gson.fromJson(input.getJSONObject(i).toString(), Location.class);;

Sorry for the stupid question.

daemon54
  • 1,057
  • 3
  • 16
  • 36

5 Answers5

54

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);
Deepak Goel
  • 5,624
  • 6
  • 39
  • 53
JRaymond
  • 11,625
  • 5
  • 37
  • 40
  • It should be "new JsonParser().parse(...)".. spent few minutes trying to figure out what the problem was – Lampione Apr 27 '16 at 18:18
13

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);
electrobabe
  • 1,549
  • 18
  • 17
3

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);
JeeHom
  • 41
  • 4
2

Convert JSONObject to Model class::

val jsonObject = JSONObject(data[0].toString())
val jsonModel = jsonObject.getJSONObject(KEY.message).toString()
val chatModel = Gson().fromJson(model, ChatModel::class.java))
1

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)
Prakash Reddy
  • 944
  • 10
  • 20