英文:
Java: Gson: fromJson: Get element value
问题
以下是翻译好的内容:
我有一个 JSON 字符串:
string jsonString = "{
\"Header\":{
\"ID\": \"103\",
\"DateTime\": \"2020-07-29 09:14:23.802-4:00 1\",
\"PlazaID\": \"01\",
\"Lane\": \"Lane 20\",
\"IPAddr\": \"192.9.0.123\"
},
\"Body\": {
\"EventMsg\": \"Status: Online\",
\"EventNum\": \"99999\"
}
}";
我正试图使用 Gson 从上述 JSON 中获取 ID 的值,但是它给了我一个 NullPointerException。我的代码:
JsonObject jsonObject = new Gson().fromJson(jsonString, JsonObject.class );
//System.out.println("jsonObject: " + jsonObject.toString());
String _ID = jsonObject.get("ID").getAsString();
我不确定我的代码哪里出错了。非常感谢帮助。
编辑:
根据 @Arvind 的建议,我尝试了他的代码,但是我得到了这个错误:
[![查看图片描述][1]][1]
根据 @Arvind 的建议,这段代码有效:
String _ID = jsonObject.get("Header").getAsJsonObject().get("ID").getAsString();
英文:
I have a json string as:
string jsonString = "{"Header":{"ID": "103","DateTime": "2020-07-29 09:14:23.802-4:00 1","PlazaID": "01","Lane": "Lane 20","IPAddr": "192.9.0.123"},"Body": {"EventMsg": "Status: Online","EventNum": "99999"}}";
I am trying to get the value if ID from the above json by using Gson and it gives me NullPointerException. My code:
JsonObject jsonObject = new Gson().fromJson(jsonString, JsonObject.class );
//System.out.println("jsonObject: " + jsonObject.toString());
String _ID = jsonObject.get("ID").getAsString();
I am not sure where the error in my code is. Any help is appreciated.
Edit:
As per @Arvind's suggestion, I tried his code and am getting this error:
As per @Arvind's suggestion, this works:
String _ID = jsonObject.get("Header").getAsJsonObject().get("ID").getAsString();
答案1
得分: 1
让我们首先美化你的 jsonString
以便更清晰地看到:
{
"Header": {
"ID": "103",
"DateTime": "2020-07-29 09:14:23.802-4:00 1",
"PlazaID": "01",
"Lane": "Lane 20",
"IPAddr": "192.9.0.123"
},
"Body": {
"EventMsg": "Status: Online",
"EventNum": "99999"
}
}
注意 "ID"
位于 "Header"
内部,因此您需要以这种方式解析:
String _ID = jsonObject.getJsonObject("Header").get("ID").getAsString();
此外,避免使用 get()
,因为有更好的便利方法:
String _ID = jsonObject.getJsonObject("Header").getString("ID");
英文:
Let's prettify your jsonString
first for clarity:
{
"Header": {
"ID": "103",
"DateTime": "2020-07-29 09:14:23.802-4:00 1",
"PlazaID": "01",
"Lane": "Lane 20",
"IPAddr": "192.9.0.123"
},
"Body": {
"EventMsg": "Status: Online",
"EventNum": "99999"
}
}
Notice that "ID"
is inside "Header"
, so you'd have to parse it this way:
String _ID = jsonObject.getJsonObject("Header").get("ID").getAsString();
Also, avoid using get()
since there are better convenience methods:
String _ID = jsonObject.getJsonObject("Header").getString("ID");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论