仅从 Java 中的 JSON 字符串中检索一个字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43055027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve just one field from JSON string in Java
提问by p0tta
Is there a way to just one field from the JSON string? My code is as follows:
有没有办法只从 JSON 字符串中提取一个字段?我的代码如下:
Object obj = parser.parse(resp);
System.out.println(obj);
JSONArray array = new JSONArray();
array.add(obj);
JSONObject obj2 = (JSONObject)array.get(0); //Getting NPE here
//Object obj3 = obj2.get("data");
System.out.println("Data: " + obj2.get("data"));
//System.out.println("Email: " + obj3.get("email_address"));
I'm using the following libraries
我正在使用以下库
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
From the response string resp, I just need data.email_address. I am unable to find a way to do it.
从响应字符串 resp,我只需要 data.email_address。我无法找到一种方法来做到这一点。
回答by Lóránt Viktor Gerber
So if this is your input:
因此,如果这是您的输入:
{
"data": {
"email_address": "[email protected]"
}
}
You first will need to make it a JSONObject
:
您首先需要将其设为JSONObject
:
JSONObject object = (JSONObject) new JSONParser().parse(json);
And then you can get data
, another JSONObject
:
然后你可以得到data
另一个JSONObject
:
JSONObject data = (JSONObject) object.get("data")
And from your data
Object you can get email_address
:
从你的data
对象你可以得到email_address
:
String email = data.get("email_address").toString();
If your input is an array of users, like this:
如果您的输入是一组用户,如下所示:
{
"users": [
{
"data": {
"email_address": "[email protected]"
}
},
{
"data": {
"email_address": "[email protected]"
}
}
]
}
You can get it the same way:
你可以用同样的方式得到它:
JSONObject object = (JSONObject) new JSONParser().parse(json);
JSONArray users = (JSONArray) object.get("users");
JSONObject user0 = (JSONObject) users.get(0);
JSONObject user0data = (JSONObject) user0.get("data");
String email = user0data.get("email_address").toString();
First parse the whole JSON into an Object. Then get an array called users
, from that array, get index 0. From that Object, get data
, and then email_address
首先将整个 JSON 解析为一个对象。然后获取一个名为 的数组users
,从该数组中获取索引 0。从该对象中获取data
,然后email_address
回答by Michael Hibay
The other option is to use jsonpath.
另一种选择是使用jsonpath。
Using the same Json blob as Lorant:
使用与 Lorant 相同的 Json blob:
{
"data": {
"email_address": "[email protected]"
}
}
You would use the following expression.
您将使用以下表达式。
$.data.email_address
Or if it was an array, simply.
或者如果它是一个数组,简单地说。
$.users.[data].email_address
An online toolcan be used to experiment and learn the syntax, but if you know xpath it should be somewhat familiar already.
一个在线工具,可以用来进行实验和学习语法,但如果你知道XPath的应该是比较熟悉了。