Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

android - How do I convert a JSONObject to class object?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...