28

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.

0

5 Answers 5

57

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); 
Sign up to request clarification or add additional context in comments.

1 Comment

It should be "new JsonParser().parse(...)".. spent few minutes trying to figure out what the problem was
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); 

3 Comments

what is ObjectMapper here..?
I guess:com.fasterxml.jackson.databind.ObjectMapper
How is it connected to gson?
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); 

Comments

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)) 

Comments

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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.