Why after elements are put into JSONArray They are mixed? - java

Working with StringBuilder came across a problem. I need to put a StringBuilder in JSONArray, but when i did my string is shuffled. How can I fix this?
My line before:
[{"id":"iprod","name":"soup","categoryId":"categoryId123","categoryName":"soup","imageUrl":"c/image","price":5.0,"weight":123.0,"ingredients":["chicken","rice"],"nutrition":{"energy":{"kilojoules":123,"kilocalories":123},"fat":123,"carbohydrate":123,"protein":123},"currency":"123"}]
My line after:
[{"nutrition":{"protein":123,"fat":123,"carbohydrate":123,"energy":{"kilojoules":123,"kilocalories":123}},"price":5,"imageUrl":"c/image","name":"soup","weight":123,"ingredients":["chicken","rice"],"currency":"123","id":"iprod","categoryName":"soup","categoryId":"categoryId123"}]
Code:
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
System.out.println(sb.toString());
JSONArray responseObject = new JSONArray(sb.toString());
System.out.println(responseObject.get(0));

Your String is JSONObject not JSONArray.
From the JSON specification at http://www.json.org/
An object is an unordered set of
name/value pairs
JSON libraries are free to rearrange the order of the elements as they see fit. GSON, a Java library developed by Google for handling JSON. And it will save the order for you:
This is the code:
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class Test {
public static void main(String[] args) {
Gson gson = new Gson();
String line = "{\"id\":\"iprod\",\"name\":\"soup\",\"categoryId\":\"categoryId123\",\"categoryName\":\"soup\",\"imageUrl\":\"c/image\",\"price\":5.0,\"weight\":123.0,\"ingredients\":[\"chicken\",\"rice\"],\"nutrition\":{\"energy\":{\"kilojoules\":123,\"kilocalories\":123},\"fat\":123,\"carbohydrate\":123,\"protein\":123},\"currency\":\"123\"}\n";
System.out.println(line);
JsonObject responseObject = gson.fromJson(line, JsonObject.class);
System.out.println(responseObject.keySet());
}
}

Related

How to access the nested field in json using Java?

I have a big JSON file(demo.json). Here is how it looks like:
{
"preview":false,
"result":{
"search_term":"rania",
"request_time":"Sat Apr 01 12:47:04 -0400 2017",
"request_ip":"127.0.0.1",
"stats_type":"stats",
"upi":"355658761",
"unit":"DR",
"job_title":"Communications Officer",
"vpu":"INP",
"organization":"73",
"city":"Wash",
"country":"DC",
"title":"Tom",
"url":"www.demo.com",
"tab_name":"People-Tab",
"page_name":"PEOPLE",
"result_number":"5",
"page_num":"0",
"session_id":"df234f468cb3fe8be",
"total_results":"5",
"filter":"qterm=rina",
"_time":"2017-04-01T12:47:04.000-0400"
}
}
{"preview"......}
{"preview"......}
....
I would like to access search term and page_name which is inside of the result and convert them into the string . Below is my java code which is not working:
BufferedReader br = new BufferedReader(new FileReader("demo.json"));
String line;
while ((line = br.readLine()) != null) {
JSONParser parser = new JSONParser();
Object obj = parser.parse(line);
JSONObject jsonObject = (JSONObject) obj;
String searchterm= (String) jsonObject.get("search_term");
String page_name = (String) jsonObject.get("page_name");
}
I am not familiar with how to access the nested fields and convert those into string. Any help is appreciated.
boolean preview = jsonObject.get("preview");
JSONObject result = jsonObject.getJSONObject("result");
String search_term = result.getString("search_term");
String page_name = result.getString("page_name");
You can use library like Gson .Convert the data into Map
BufferedReader br = new BufferedReader(new FileReader("demo.json"));
String line;
StringBuilder builder=new StringBuilder();
while ((line = br.readLine()) != null) {
builder.append(line);
}
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(builder.toString(), type);
You can use myMap to get Values for json Keys . For nested Key you can another convert it to Map again.
Use ObjectMapper to convert your JSON to PoJo and then use it.

Parsing JSON response(includes a list) in java

I did a http client and I'm getting a response. I am using a JSONObject to parse the data and when I execute the code below it prints out all of the JSON just fine
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if(entity!=null){
try(InputStream instream = entity.getContent()) {
String responseString = readInputStream(instream);
JSONObject job = new JSONObject(responseString);
statusLabel.setText("Command Result: " + job.toString());
Here is the readInputSream function:
static private String readInputStream(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "UTF-8"));
String tmp;
StringBuilder sb = new StringBuilder();
while ((tmp = reader.readLine()) != null) {
sb.append(tmp).append("\n");
}
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\n') {
sb.setLength(sb.length() - 1);
}
reader.close();
return sb.toString();
}
If I change it from job.toString() to:
statusLabel.setText("Command Result: " + job.get("result"));
it prints a 1 which is correct, it works all the way up to my_list. I'm not sure how to parse the list. I put a snippet of the response below. Ive tried "my_list", "my_list[]", my_list[0]" which none have worked. I get JSONObject "blank" not found
{"result":1, "ver":1,"total":2,"catch":true,"my_list":[{"id":3,"mid":0,"format":3,"user":4,"property":1,"type":0,"title":"hello","start":146,"end":1464,"hid":3,"bid":1,"reason":1,"time":0,"creator":"1","hello":0,"my":0,"year":"0","ggg":614,"name":"","ch":"0","attr":0,"type":1,"vtype":1,"tm_log": {"fr":4,"action":0,"vr":"82","started":1,"av_ended":2,"tr":1}}
The element you trying to retrieve is parsed into a JSONArray, not a JSONObject. Try:
JSONArray my_list = job.getJSONArray("my_list");
Assuming that you are using json parser project JSON-java to parse your JSON you need to retrieve a JSONArray instance - this is how arrays are storred in JSONObject. so do the following: JSONArray my_list = job.getJSONArray("my_list"); and then use methods of JSONArray class to access your array. The Javadoc to JSON-java package can be found here: http://stleary.github.io/JSON-java/index.html. Also note that JSON-java is very simple and easy to use JSON parser project but it is not very efficient for any serious project. Common recommendation for commercial use is Jackson JSON Processor which is one of the fastest and powerful JSON parsers. Here are some links to read about it: https://github.com/FasterXML/jackson, http://wiki.fasterxml.com/JacksonHome

Parsing json file content in java

I have a json file which contains below json data.
[{"id":1025,
"key":"SVS",
"prj_name":"SVS",
"prj_scope":"PR8",
"prj_qualifier":"WW",
"date":"2016-03-29T06:00:26-0400",
"creationDate":"2013-04-12T09:03:35-0400",
"prj_lname":"SVS",
"csr":[{"key":"test_success","test_output":85.3,"org_val":"78.3%"}]}]
I want to read test_output value in java. I tried with few json-simple api. Below is the code which I wrote.
StringBuffer sbf = new StringBuffer();
FileReader fileReader = new FileReader("C:/Users/java_backups/Downloads/output.json");
BufferedReader br = new BufferedReader(fileReader);
String line="";
while ((line = br.readLine()) != null) {
sbf.append(line);
}
System.out.println(sbf.toString());
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray= (JSONArray) jsonParser.parse(sbf.toString());
size of jsonArray is one only. I do not have any clue how can I read test_output value from json string.
Using Jackson for simplicity:
public class Test {
private static final String JSON = "[{\"id\":1025,\"key\":\"SVS\",\"prj_name\":\"SVS\",\"prj_scope\":\"PR8\",\"prj_qualifier\":\"WW\",\"date\":\"2016-03-29T06:00:26-0400\",\"creationDate\":\"2013-04-12T09:03:35-0400\",\"prj_lname\":\"SVS\",\"csr\":[{\"key\":\"test_success\",\"test_output\":85.3,\"org_val\":\"78.3%\"}]}]";
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(JSON);
System.out.println(actualObj.findValue("test_output"));
}
}
Dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.3</version>
</dependency>
If you only have 1 output with the given name in each JsonObject, this will do the trick. Just iterate over the JsonArray and find the value for each JsonObject. In case your array is always just 1 element, just ignore the iteration part and simply use it as I did above.

How to parse multipe json value in java

I've below json value in my StringBuilder variable, I want to parse all id key value and store it again in StringBuilder.
{"status":"success","id":"1"}
{"status":"success","id":"2"}
{"status":"success","id":"3"}
{"status":"success","id":"4"}
{"status":"success","id":"5"}
{"status":"success","id":"6"}
Expected output:
1
2
3
4
5
6
How can I parse these value in java?
I tried below option but it doesn't help:
StringBuilder str = new StringBuilder();
str.append(jsonStringValue);
JSONObject jObj = new JSONObject(str);
jObj.getString("id");
Using JSONTokener
JSONTokener t = new JSONTokener(str.toString());
while (t.more()) {
JSONObject o2 = (JSONObject) t.nextValue();
System.out.println(o2.getString("id"));
}
But I'm getting below error message:
org.json.JSONException: Missing value at character 128
If you're using org.json, You can use JSONTokener.
Here's example shows how it works.
public static void main(String args[]) throws JSONException {
String str1 = "{\"strValue\":\"string\"}\n{\"intValue\":1}";
JSONTokener t = new JSONTokener(str1);
JSONObject o1 = (JSONObject) t.nextValue();
JSONObject o2 = (JSONObject) t.nextValue();
System.out.println(o1.getString("strValue"));
System.out.println(o2.getLong("intValue"));
System.out.println(t.more()); // Check if there's more token. can be used to process with loop.
}
Or if you can change input string, you can put those object into Json array.
[
{"status":"success","id":"1"},
{"status":"success","id":"2"},
{"status":"success","id":"3"},
{"status":"success","id":"4"},
{"status":"success","id":"5"},
{"status":"success","id":"6"}
]
In that case you can use org.json.JSONArray to handle it.
You can use regexps like this
public class Test {
public static void main(String[] args) {
StringBuilder inputBuf = prepareStringBuilder();
StringBuilder outputBuf = new StringBuilder();
Pattern pattern = Pattern.compile(":\"(\\d+)\"");
Matcher matcher = pattern.matcher(inputBuf);
while (matcher.find()) {
String group = matcher.group(1);
outputBuf.append(group);
}
System.out.println(outputBuf);
}
private static StringBuilder prepareStringBuilder() {
StringBuilder buf = new StringBuilder();
buf.append("{\"status\":\"success\",\"id\":\"1\"}");
buf.append("{\"status\":\"success\",\"id\":\"2\"}");
buf.append("{\"status\":\"success\",\"id\":\"3\"}");
buf.append("{\"status\":\"success\",\"id\":\"4\"}");
buf.append("{\"status\":\"success\",\"id\":\"5\"}");
buf.append("{\"status\":\"success\",\"id\":\"6\"}");
return buf;
}
}

How to extract multiple JSON Objects into String

I am reading multiple JSONObject from a file and converting into a string using StringBuilder.
These are the JSON Objects.
{"Lng":"-1.5908601","Lat":"53.7987816"}
{"Lng":"-2.5608601","Lat":"54.7987816"}
{"Lng":"-3.5608601","Lat":"55.7987816"}
{"Lng":"-4.5608601","Lat":"56.7987816"}
{"Lng":"-5.560837","Lat":"57.7987816"}
{"Lng":"-6.5608294","Lat":"58.7987772"}
{"Lng":"-7.5608506","Lat":"59.7987823"}
How to convert into a string?
Actual code is:-
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
catch(IOException e)
{
msg.Log(e.toString());
}
String contentsAsString = builder.toString();
//msg.Log(contentsAsString);
I tried this code
JSONObject json = new JSONObject(contentsAsString);
Iterator<String> iter = json.keys();
while(iter.hasNext())
{
String key = iter.next();
try{
Object value = json.get(key);
msg.Log("Value :- "+ value);
}catch(JSONException e)
{
//error
}
}
It just gives first object. How to loop them?
try this and see how it works for you,
BufferedReader in
= new BufferedReader(new FileReader("foo.in"));
ArrayList<JSONObject> contentsAsJsonObjects = new ArrayList<JSONObject>();
while(true)
{
String str = in.readLine();
if(str==null)break;
contentsAsJsonObjects.add(new JSONObject(str));
}
for(int i=0; i<contentsAsJsonObjects.size(); i++)
{
JSONObject json = contentsAsJsonObjects.get(i);
String lat = json.getString("Lat");
String lng = json.getString("Lng");
Log.i("TAG", lat + lng)
}
What you do is you are loading multiple JSON objects into one JSON object. This does not make sense -- it is logical that only the first object is parsed, the parser does not expect anything after the first }. Since you want to loop over the loaded objects, you should load those into a JSON array.
If you can edit the input file, convert it to the array by adding braces and commas
[
{},
{}
]
If you cannot, append the braces to the beginning of the StringBuilder and append comma to each loaded line. Consider additional condition to eliminate exceptions caused by inpropper input file.
Finally you can create JSON array from string and loop over it with this code
JSONArray array = new JSONArray(contentsAsString);
for (int i = 0; i < array.length(); ++i) {
JSONObject object = array.getJSONObject(i);
}

Categories

Resources