我收到一个JSON对象数组,其中一部分如下所示:
[{"Team":"LTD","Amount":10000.0,"Success":true},
{"Team":"XYZ","Amount":50000.0,"Success":false}]我想以字符串的形式强行读取所有字段,以使进一步的处理变得简单和统一。因此,Amount必须被理解为10000.0而不是1.0E5。
下面是我使用的代码片段:
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当我从Amount打印resultList的值和类型时,它们分别显示为1.0E5和String。在解析和读取之间,从Double到String的转换似乎以意想不到的方式发生。
我读了一篇类似的文章here,它解决了一个有点不同的问题。
将提取的inputStream和fields将在运行时提供。因此,使用POJO和其他需要定义类的方法是行不通的。
发布于 2019-03-14 14:05:43
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 mentionedJSON :
{
"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"));
}
}https://stackoverflow.com/questions/55161793
复制相似问题