I have a problem when using GSON library which is json library from Google. Hope someone can give me some hint.
The problem is when I use the gson.fromJson() function trying to convert a json string to a specified defined class.
The example code:
String jsonStr = "{name:"ABC", countries:["US"]}"; // Some Json string.
Gson gson = new Gson();
Example example = gson.fromJSON(jsonStr, Example.class);
class Example {
// does no have no-arg constructor
private String name;
private Integer age;
private JSONArray keywords; // import org.json.JSONArray;
private JSONArray countries;
// other codes
}
The above code is simplied version of my problem. The problem is in the fromJson() function. The error message is saying "JsonParseException: Expecting object found ["US"]".
I can not figure out what the problem is. I guess maybe gson does not know how to covert a 开发者_开发问答string to JSONArray. Because in here, JSONArray is from another library(org.json).
I try to figure out in the gson documents. It look like I need to write some "Instance Creator" code.
I am wondering whether another can give me some solution. Thank you.
Just make keywords and countries a java List type. I've never seen org.json mixed with gson. Usually gson replaces org.json it's not meant to be used together.
EDIT:
Small example:
class Example {
private String name;
private Integer age;
private List<String> keywords;
private List<String> countries;
public String toString() {
return new Gson().toJson(this);
}
}
精彩评论