【发布时间】:2014-07-29 00:24:35
【问题描述】:
我从服务器接收到类似于以下语法的 JSON,我需要一些帮助来反序列化和解析它。我对此进行了大量阅读,发现使用 GSON 真的很有用! (我会在这里发布我的代码的任何更新)
(更正的 JSON):
[{
"name" : "Zone1",
"types" : [{"datatype":"string","brand":"string","index":0},
{"datatype":"string","value":"int32,"index":1},
{"datatype":"string","url":"string,"index":2}]
"data" : [["gucci",2,"www.whoami12345.com"]]
},
{
"name" : "Zone2",
"types" : [{"datatype":"string","brand":"string","index":0},
{"datatype":"string","value":"int32,"index":1},
{"datatype":"string","url":"string,"index":2}]
"data" : [["nike", 23,"www.nike.com"]]
}]
我发现这个网站Link 非常简洁,因为它解释了如何使用 gson 并很好地解释了反序列化。我对 JSON 的理解是它是一个数组,而数据字段是一个数组数组。
我的问题是如何解析这个?我有一个函数可以用字符串搜索特定的区域名称。在进行反序列化并且条目与正确的区域匹配后,应该返回数据类型和 url。从那篇文章中,我的理解是我应该使用 JSONArray。对于任何反馈,我们都表示感谢。下面是我开始的一些代码
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
String name;
public class data{
String brand;
int num;
int url;
}
public class types{
String datatype;
int value;
String url;
}
public types Deserialiser(String json, String zone){ // this is the json string that will be passed into the function
JsonObject jsonObject = json.getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray();
int index = -1;
for (int i = 0; i<jsonArray.size();i++){
String temp = jsonArray.get(i).get("name");
if (temp.equals(zone){
index =i;
break;
}
}
....
types jsonTypes = new types();
// set everything else
return jsonTypes;
}
【问题讨论】:
-
对。那不是(有效的)JSON。如果您打印出您的
json字符串,您会发现它与您在 json.org 上找到的语法不匹配。 -
仍然不是有效的 JSON。
-
提示:第 1、2、5、7 行有 bug。
-
1 秒让我纠正这个问题
-
至于你如何解析它,你有一个地图列表。三个 Map 键中的两个对应于 List,其中一个 List 包含另一个 List。 (如果你去 json.org 学习语法,这会更有意义。)
标签: java json gson deserialization