Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a JSONObject to class object?

Tags:

android

gson

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.

like image 236
daemon54 Avatar asked Mar 07 '13 21:03

daemon54


1 Answers

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); 
like image 139
JRaymond Avatar answered Oct 18 '22 18:10

JRaymond