I receive an array of JSON objects, a part of which is below:
[{"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
.
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. In between parsing and reading, the conversion from Double
to String
seems to occur in unexpected way.
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. Hence, using POJO and other methods that need to define Class won't work.
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 :
{
"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"));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.