A有来自Json的硬串。示例:
[
{
"Group1": [
{
"id": "2b3b0db",
"name": "Ivan"
},
{
"id": "4f3b0db",
"name": "Lera"
}
]
},
{
"Group2": [
{
"id": "42ae2a7",
"name": "Victor"
}
]
}
]
我如何从Gson解析它?谢谢!
答案 0 :(得分:2)
此链接使用Gson
描述json到java和java到jsonhttp://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
使用GSON的Json到Java
Gson gson = new Gson();
try {
BufferedReader br = new StringReader(<CONTENT>);
//convert the json string back to object
// In your case this is Group object
Object obj = gson.fromJson(br, Object .class);
System.out.println(obj);
} catch (IOException e) {
e.printStackTrace();
}
使用GSON的Java对象到json String
Object obj = new Object();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
在您的情况下使用此:
public static void main(final String[] args) {
String Group1 = " [ { \"id\": \"2b3b0db\", \"name\": \"Ivan\" }, { \"id\": \"4f3b0db\", \"name\": \"Lera\" } ] ";
Gson gson = new Gson();
Group[] object = gson.fromJson(new StringReader(Group1), Group[].class);
System.out.println(object);
}
public class Group {
private String id;
private String name;
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public void setId(final String id) {
this.id = id;
}
}
答案 1 :(得分:1)
尝试以下代码
public String parse(String jsonLine)
{
JSONArray jArraymain=new JSONArray(jsonLine);
JSONObject jobject=array.getJSONObject(0);
JSONArray jArraySub=jobject.getJSONArray("Group1");
for(int i=0;i<=jobject.length;i++)
{
String temp=jArraySub.get(i).toString();
}
}
also you can use this
public String parse(String jsonLine) {
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("data");
JsonArray jarray = jobject.getAsJsonArray("translations");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("translatedText").toString();
return result;
}
答案 2 :(得分:0)
以下将帮助您。我还没有执行下面的代码片段。
JsonElement jelement = new JsonParser().parse("json data");
JsonArray jgrouparray = jelement.getAsJsonArray();
for(int i=0; i<jgrouparray.size(); i++){
JsonArray jgroup = jgrouparray.get(i).getAsJsonArray("Group"+i);
for(int j=0; j<jgroup.size(); j++){
JsonObject jobject = jgroup.get(j).getAsJsonObject();
String id = jobject.get("id").toString();
String name = jobject.get("name").toString();
}
}
有关详细信息,请查看:JSON parsing using Gson for Java
答案 3 :(得分:0)
你必须使用GSON吗?如果你可以使用json.org中的JSONObject,你几乎可以得到它:
URL url = this.getClass().getClassLoader().getResource("json" + File.separator + "GroupJson.json");
JSONArray jsonArray = new JSONArray(FileUtil.readFile(url.getPath()));
JSONObject jsonObject = jsonArray.getJSONObject(0);
log.info("{}", jsonObject.toString());
此输出:{“Group1”:[{“id”:“2b3b0db”,“name”:“Ivan”},{“id”:“4f3b0db”,“name”:“Lera”}}} < / p>