[英]Jayway JsonPath read String Java
I receive an array of JSON objects, a part of which is below: 我收到一个JSON对象数组,其中一部分如下:
[{"Team":"LTD","Amount":10000.0,"Success":true},
{"Team":"XYZ","Amount":50000.0,"Success":false}]
I want to forcefully read all fields as string so as to make further processing easy and uniform. 我想强制读取所有字段作为字符串,以便进一步处理容易和统一。 So Amount
must be read as 10000.0
and not as 1.0E5
. 因此, Amount
必须读取为10000.0
而不是1.0E5
。
Below is the code snippet that I use : 以下是我使用的代码段:
String input=IOUtils.toString(inputStream);
String[] fields="Amount|Success".split("\\|");
ReadContext inputParsed =JsonPath.parse(input);
List<JSONArray> resultList=Arrays.stream(fields)
.map(x -> inputParsed.read("$[*]."+x,JSONArray.class))
.collect(Collectors.toList());
//Further code to process resultList
When I print the values and type of Amount
from resultList
, they are shown as 1.0E5
and String
respectively. 当我从resultList
打印Amount
的值和类型时,它们分别显示为1.0E5
和String
。 In between parsing and reading, the conversion from Double
to String
seems to occur in unexpected way. 在解析和读取之间,从Double
到String
的转换似乎以意想不到的方式发生。
I read a similar post here and it addresses a bit different problem. 我在这里读了一篇类似的文章,它解决了一些不同的问题。
The inputStream
and fields
, which are to be extracted , will be provided at run time. 将在运行时提供要提取的inputStream
和fields
。 Hence, using POJO and other methods that need to define Class won't work. 因此,使用POJO和其他需要定义Class的方法将不起作用。
1. You should download **org.json.jar** this is used to convert json to what you need(String,int,etc),
2. Change your json format like below i mentioned
JSON : JSON:
{
"data":[
{
"Team":"LTD",
"Amount":10000.0,
"Success":true
},
{
"Team":"XYZ",
"Amount":50000.0,
"Success":false
}
]
}
public static void main(String[] arg) throws JSONException {
String arr = "{ \n"
+ " \"data\":[ \n"
+ " { \n"
+ " \"Team\":\"LTD\",\n"
+ " \"Amount\":10000.0,\n"
+ " \"Success\":true\n"
+ " },\n"
+ " { \n"
+ " \"Team\":\"XYZ\",\n"
+ " \"Amount\":50000.0,\n"
+ " \"Success\":false\n"
+ " }\n"
+ " ]\n"
+ "}";
JSONObject obj = new JSONObject(arr);
JSONArray data = obj.getJSONArray("data");
int n = data.length();
for (int i = 0; i < n; ++i) {
final JSONObject dt = data.getJSONObject(i);
System.out.println(dt.getString("Team"));
System.out.println(dt.getString("Amount"));
System.out.println(dt.getBoolean("Success"));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.