当我向服务器发送请求时。 我得到这种格式的结果数据:
{
"menu": {
"7": [{
"m_id": "1",
"m_flag": "1",
"m_type": "7",
"m_name": "\u30cf\u30a4\u30cd\u30b1\u30f3",
"m_price": "1000",
"m_cost": "158",
"m_regist_date": "0000-00-00",
"p_id": "0"
}, {
"m_id": "2",
"m_flag": "1",
"m_type": "7",
"m_name": "\u30ae\u30cd\u30b9",
"m_price": "1000",
"m_cost": "250",
"m_regist_date": "0000-00-00",
"p_id": "0"
},....
"2": [{
"m_id": "149",
"m_flag": "1",
"m_type": "2",
"m_name": "\u30da\u30fc\u30bf\u30fc\u30e4\u30b3\u30d6\u30ea\u30fc\u30b9\u30ea\u30f3\u30b0",
"m_price": "6500",
"m_cost": "2100",
"m_regist_date": "0000-00-00",
"p_id": "0"
}, {
"m_id": "150",
"m_flag": "1",
"m_type": "2",
"m_name": "\u30a4\u30d3\u30b9\u30af\u30b9 \u30eb\u30fc\u30b8\u30e5 08",
"m_price": "6800",
"m_cost": "2520",
"m_regist_date": "0000-00-00",
"p_id": "0"
},...
}
很长。所以当我使用时:
JSONObject json = jsonParser.makeHttpRequest(REQUEST_URL, "POST",params);
menu = json.getJSONArray("menu");
我收到错误,无法获取JSON数据:
Error parsing data org.json.JSONException: End of input at character 0 of
我如何解析json的数据,我不知道如何使用Gson。 以及如何获取KEY" 2"的数据。 非常感谢你!
答案 0 :(得分:0)
如果您正在寻找GSON
解析,请在此处找到它。
只需创建一个POJO类并将其映射到JSON字符串。
示例代码:
class MenuDetail {
private String m_id;
private String m_flag;
private String m_type;
private String m_name;
private String m_price;
private String m_cost;
private String m_regist_date;
private String p_id;
// getter & setter
}
...
Type type = new TypeToken<Map<String, Map<String, ArrayList<MenuDetail>>>>() {}.getType();
Map<String, Map<String, ArrayList<MenuDetail>>> data = new Gson().fromJson(json, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
输出:
{
"menu": {
"7": [
{
"m_id": "1",
"m_flag": "1",
"m_type": "7",
"m_name": "name",
"m_price": "1000",
"m_cost": "158",
"m_regist_date": "0000-00-00",
"p_id": "0"
},
{
"m_id": "2",
"m_flag": "1",
"m_type": "7",
"m_name": "name",
"m_price": "1000",
"m_cost": "250",
"m_regist_date": "0000-00-00",
"p_id": "0"
}
]
}
}