java - Using Gson to unserialize an array of objects -
i have json response looks this. want extract values of "text" , put them set of strings (i.e. don't need entire json derialised).
i using gson library
so far method looks (it's wrong):
public static response deserialise(string json){ gson gson = new gson(); response r = gson.fromjson(json, response.class); return r; }
i calling deserialise
this:
response r = deserialise(json); system.out.println("[status]: "+r.getstatus()); // works fine collection<keyword> coll = r.getkeywords(); iterator<keyword> itr = coll.iterator(); while(itr.hasnext()){ system.out.println(itr.next().getword()); //prints null every time }
response class following member variables (with getters , setters):
private string status; private string usage; private string language; private collection<keyword> keywords;
keyword class following member variables (with getters , setters):
private string word; private string relevance;
the json looks this:
{ "status": "ok", "usage": "by accessing alchemyapi or using information generated alchemyapi, agreeing bound alchemyapi terms of use: http://www.alchemyapi.com/company/terms.html", "url": "http://www.theage.com.au/world/aussie-trying-to-make-a-difference-gunned-down-20110510-1egnv.html", "language": "english", "keywords": [ { "text": "mr mcnichols", "relevance": "0.99441" }, { "text": "ms benton", "relevance": "0.392337" }, { "text": "detroit", "relevance": "0.363931" }, { "text": "crocodile hunter", "relevance": "0.350197" } ] }
the problem collection of keywords returns null values - although seems have correct size, positive.
this works:
public class keyword { public string text; public string relevance; } public class myjson { public string status; public string usage; public string language; public collection<keyword> keywords; }
in main method
string str = "{\"status\": \"ok\","+ "\"usage\": \"by accessing alchemyapi or using information generated alchemyapi, agreeing bound alchemyapi terms of use: http://www.alchemyapi.com/company/terms.html\","+ "\"url\": \"http://www.theage.com.au/world/aussie-trying-to-make-a-difference-gunned-down-20110510-1egnv.html\","+ "\"language\": \"english\","+ "\"keywords\": ["+ "{"+ "\"text\": \"mr mcnichols\","+ "\"relevance\": \"0.99441\""+ "},"+ "{"+ "\"text\": \"ms benton\","+ "\"relevance\": \"0.392337\""+ "},"+ "{"+ "\"text\": \"detroit\","+ "\"relevance\": \"0.363931\""+ "},"+ "{"+ "\"text\": \"crocodile hunter\","+ "\"relevance\": \"0.350197\""+ "}"+ "]"+ "}"; gson gson = new gson(); myjson mj = gson.fromjson(str, myjson.class); system.out.println(mj.language); for(keyword k: mj.keywords) system.out.println(k.text+":"+k.relevance);
this prints
english mr mcnichols:0.99441 ms benton:0.392337 detroit:0.363931 crocodile hunter:0.350197
look @ keyword class!(and json string starts {
).
Comments
Post a Comment