Parsing json file content in java - 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.

Related

Why after elements are put into JSONArray They are mixed?

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());
}
}

JSON Stream parsing crashes at the end of the object

I am struggling with some JSON parsing (with Google's GSON library).
Here is my minimal code example:
Gson gson = new Gson();
String line = "{\"method\":\"GET\",\"status\":\"200 - OK\"}";
AnalysisReport report = gson.fromJson(line, AnalysisReport.class); //this works
JsonReader reader = new JsonReader(new StringReader(line));
reader.setLenient(true); //accept malformed input
while (reader.hasNext()) {
report = gson.fromJson(reader, AnalysisReport.class); //this doesn't work
}
reader.close();
I get the following exception: (the string is 36 chars long)
Expected BEGIN_OBJECT but was END_DOCUMENT at line 1 column 37
My ReportAnalysis class looks like this:
public class AnalysisReport {
#SerializedName("method")
private String method;
#SerializedName("status")
private String status;
AnalysisReport(){
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getStatus() {
return status;
}
}
I do not see why my code is not working. I followed the exmaple from Google
= = = EDIT = = =
The reader.hasNext() method always returns true. It seams that the method does not consume any tokens from the stream. But somehow still moves to the end of the stream and failes reading objects.
The problem was indeed the loop (facepalm). This works perfectly fine:
JsonReader reader = new JsonReader(new StringReader(line));
reader.setLenient(true); //accept malformed input
report = gson.fromJson(reader, AnalysisReport.class);
Thanks
I just removed loop and its working fine .
String line = "{\"method\":\"GET\",\"status\":\"200 - OK\"}";
AnalysisReport report = new AnalysisReport();
Gson gson = new GsonBuilder().create();
JsonReader reader = new JsonReader(new StringReader(line));
reader.setLenient(true); //accept malformed input
report = gson.fromJson(line, AnalysisReport.class); //this doesn't work
reader.close();
System.out.println(report.toString());

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.

Some objects can't be deserialized through Gson

I'm trying to parse the following url:
http://api.crossref.org/works?rows=2
When I parse it through Gson, I got some records but somehow some others stay null.
Here is my code:
BufferedReader in = new BufferedReader(new InputStreamReader(url_tdm.openStream(), "UTF-8"));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = in.read(chars)) != -1)
buffer.append(chars, 0, read);
String jsonLine = buffer.toString();
JsonReader reader = new JsonReader(new StringReader(jsonLine));
reader.setLenient(true); // this is for Malformed json
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();
Crossref answer = gson.fromJson(reader, Crossref.class );
List<Items> ao = answer.message.items;
public class Crossref {
public Message message;}
public class Message {
public List<Items> items;}
public class Items {
public List<String> containerTitle;
public List<String> ISSN;
public String publisher;
public List<String> title;
public String DOI;
public String type;}
So as a result of my code above, I can get container-title, publisher and title values. But ISSN and DOIs are null.
I used a FieldNamingPolicy because "container-title" contains a dash and I could not name my field like that in java (so I wrote it as camel case containerTitle).
I am not sure if this affects DOI and ISSN records which are upper case or is it something totally different?
The best way to fix something like this is to use a gson custom deserializer
I suggest that you read this other question to see a good exemple: How do I write a custom JSON deserializer for Gson?
And you can find some other greats exemples and explanations here

Convert a .json file to a JSONArray

I used cURL to get some twitter feeds in the form of a json file ("twitter-feed.json"). I want to convert this json file to a JSONArray object. How do I do it?
I am new to Java and json. Your suggestions are most welcome.
FileInputStream infile = new FileInputStream("input/twitter-feed.json");
// parse JSON
JSONArray jsonArray = new JSONArray(string);
// use
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println(jsonObject.getString("id"));
System.out.println(jsonObject.getString("text"));
System.out.println(jsonObject.getString("created_at"));
}
Thanks,
PD.
You need to read the file first, convert it to String then feed it to the JSONArray (I am assuming that you are using the JSON-Java Project. The code below illustrates how to read the file and set it to JSONArray
// read the source file, source comes from streaming API delimited by newline
// done by curl https://stream.twitter.com/1/statuses/sample.json?delimited=newline -utwitterUsername:twitterPasswd
// > /Projects/StackOverflow/src/so7655570/twitter.json
FileReader f = new FileReader("/Projects/StackOverflow/src/so7655570/twitter.json");
BufferedReader br = new BufferedReader(f);
ArrayList jsonObjectArray = new ArrayList();
String currentJSONString = "";
// read the file, since I ask for newline separation, it's easier for BufferedReader
// to separate each String
while( (currentJSONString = br.readLine()) != null ) {
// create new JSONObject
JSONObject currentObject = new JSONObject(currentJSONString);
// there are more than one way to do this, right now what I am doing is adding
// each JSONObject to an ArrayList
jsonObjectArray.add(currentObject);
}
for (int i = 0; i < jsonObjectArray.size(); i++) {
JSONObject jsonObject = jsonObjectArray.get(i);
// check if it has valid ID as delete won't have one
// sample of JSON for delete :
// {"delete":{"status":{"user_id_str":"50269460","id_str":"121202089660661760","id":121202089660661760,"user_id":50269460}}}
if(jsonObject.has("id")) {
System.out.println(jsonObject.getInt("id"));
System.out.println(jsonObject.getString("text"));
System.out.println(jsonObject.getString("created_at") + "\n");
}
}
Steps explanation :
Stream API does not provide valid JSON as a whole but rather a valid one specified by the delimited field. Which is why, you can't just parse the entire result as is.
In order to parse the JSON, I use the delimited to use newline since BufferedReader has a method readLine that we could directly use to get each JSONObject
Once I get each valid JSON from each line, I create JSONObject and add it to the ArrayList
I then iterate each JSONObject in the ArrayList and print out the result. Note that if you want to use the result immediately and don't have the need to use it later, you can do the processing itself in while loop without storing them in the ArrayList which change the code to:
// read the source file, source comes from streaming API
// done by curl https://stream.twitter.com/1/statuses/sample.json?delimited=newline -utwitterUsername:twitterPasswd
// > /Projects/StackOverflow/src/so7655570/twitter.json
FileReader f = new FileReader("/Projects/StackOverflow/src/so7655570/twitter.json");
BufferedReader br = new BufferedReader(f);
String currentJSONString = "";
// read the file, since I ask for newline separation, it's easier for BufferedReader
// to separate each String
while( (currentJSONString = br.readLine()) != null ) {
// create new JSONObject
JSONObject currentObject = new JSONObject(currentJSONString);
// check if it has valid ID as delete status won't have one
if(currentObject.has("id")) {
System.out.println(currentObject.getInt("id"));
System.out.println(currentObject.getString("text"));
System.out.println(currentObject.getString("created_at") + "\n");
}
}
You may try Gson:
For just arrays you can use:
Gson gson = new Gson();
//(Deserialization)
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);
To deserialize an array of objects, you can just do:
Container container = new Gson().fromJson(json, Container.class);
As shown here
Use ObjectMapper Class from jackson library like this :
//JSON from file to Object
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);
//JSON from URL to Object
Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class);
//JSON from String to Object
Staff obj = mapper.readValue(jsonInString, Staff.class);

Categories

Resources