Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...