How to add a method to parse a JSON file in Java - java
I am trying to parse the content of JSON file text.json by using Jackson library.
What I want is to make a java method in the following code to get all keys and values of it, but so far in my code I get only the first key and the first value of the JSON file.
Here is my Java class:
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonStreamExample {
public static void main(String[] args) {
try {
//Create a JsonFactory instance
JsonFactory factory = new JsonFactory();
//Create a JsonParser instance to read from file c:\\text.json
JsonParser jParser = factory.createJsonParser(new File("c:\\text.json"));
/*Create an ObjectMapper instance to provide a pointer
* to root node of the tree after reading the JSON
*/
ObjectMapper mapper = new ObjectMapper(factory);
//Create tree from JSON
JsonNode rootNode = mapper.readTree(jParser);
Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.getFields();
while (fieldsIterator.hasNext()) {
Map.Entry<String,JsonNode> field = fieldsIterator.next();
System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
}
jParser.close();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My Eclipse output is the following which creates only 1 pair(key-value):
Key: cells Value:[{"type":"basic.Circle","size":{"width":90,"height":54},"position":{"x":-80,"y":200},"angle":0,"id":"cae4c219-c2cd-4a4b-b50c-0f269963ca24","embeds":"","z":1,"wi_name":"START","wi_displayName":"START","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"circle":{"fill":"#000000","width":50,"height":30,"stroke-width":1,"stroke-dasharray":"0"},"text":{"font-size":10,"text":"START","fill":"#ffffff","font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"basic.Circle","size":{"width":90,"height":54},"position":{"x":210,"y":200},"angle":0,"id":"d23133e0-e516-4f72-8127-292545d3d479","embeds":"","z":2,"wi_name":"END","wi_displayName":"END","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"circle":{"fill":"#000000","width":50,"height":30,"stroke-width":1,"stroke-dasharray":"0"},"text":{"font-size":10,"text":"END","fill":"#ffffff","font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"basic.Rect","position":{"x":-80,"y":370},"size":{"width":90,"height":54},"angle":0,"id":"a53898a5-c018-45c4-bd3f-4ea4d69f58ed","embeds":"","z":3,"wi_name":"ACTIVITY_1","wi_displayName":"ACTIVITY 1","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"rect":{"width":50,"height":30,"rx":2,"ry":2,"stroke-width":1,"stroke-dasharray":"0"},"text":{"text":"Activity","font-size":10,"font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"basic.Rect","position":{"x":220,"y":370},"size":{"width":90,"height":54},"angle":0,"id":"e2bd21f2-508d-44b9-9f68-e374d4fa87ea","embeds":"","z":4,"wi_name":"ACTIVITY_2","wi_displayName":"ACTIVITY 2","wi_description":"","wi_join":"<None>","wi_split":"<None>","wi_performingRole":"<None>","wi_expected_activity_time":null,"wi_expected_user_time":null,"wi_maximum_activity_time":null,"wi_initial_delay":null,"wi_time_unit":"Seconds","wi_required_transitions_for_AND_JOIN":null,"wi_custom_page":"","attrs":{"rect":{"width":50,"height":30,"rx":2,"ry":2,"stroke-width":1,"stroke-dasharray":"0"},"text":{"text":"Workitem","font-size":10,"font-family":"Arial","stroke":"#000000","stroke-width":0,"font-weight":400}}},{"type":"link","source":{"id":"cae4c219-c2cd-4a4b-b50c-0f269963ca24"},"target":{"id":"d23133e0-e516-4f72-8127-292545d3d479"},"router":{"name":"manhattan"},"labels":[{"position":0.5,"attrs":{"text":{"text":"Name"}}}],"id":"60ee7ff7-3a3b-487d-b581-49027e7bebe4","embeds":"","z":5,"attrs":{".marker-source":{"d":"M 10 0 L 0 5 L 10 10 z","transform":"scale(0.001)"},".marker-target":{"d":"M 10 0 L 0 5 L 10 10 z"},".connection":{"stroke":"black"}}},{"type":"link","source":{"id":"a53898a5-c018-45c4-bd3f-4ea4d69f58ed"},"target":{"id":"e2bd21f2-508d-44b9-9f68-e374d4fa87ea"},"router":{"name":"manhattan"},"labels":[{"position":0.5,"attrs":{"text":{"text":"Name"}}}],"id":"cea0d1c2-2c18-4bd7-ba35-d94918c6fc9b","embeds":"","z":6,"attrs":{".marker-source":{"d":"M 10 0 L 0 5 L 10 10 z","transform":"scale(0.001)"},".marker-target":{"d":"M 10 0 L 0 5 L 10 10 z"},".connection":{"stroke":"black"}}}]
How will I do it please?
In the above code sample, the nested/Hierarchical Structure is not considered of json value and it directly prints it as field.getValue().
You'll have to check for the type of value using
if(field.getValue().isObject())
{
parse(field.getValue())
}
The Parse Method could be as follows
private void parse(JsonNode jsonNode)
{
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = jsonNode.getFields();
while (fieldsIterator.hasNext())
{
Map.Entry<String, JsonNode> field = fieldsIterator.next();
if (field.getValue().isObject())
{
parse(field.getValue());
}
System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
}
}
Then you have to just call the parse method for the rootNode.
I solved my problem by changing JSON library.
I used json-simple-1.1.1
My final code that worked is the following:
package jsontoxml;
import java.io.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.*;
import java.util.*;
public class JacksonStreamExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("text.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray cells = (JSONArray) jsonObject.get("cells");
Iterator<JSONObject> iterator = cells.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
A space in JSON value causes "unexpected token END OF FILE at position 11" exception when parsing in Java
When I use the parser from org.json.simple.parser.* I get an exception whenever one of the values in JSON contains a space. For example: {"name":"Adam"} would parse correctly, but {"name":"Ad am"} would cause "unexpected token END OF FILE at position 11" exception Here is the code that I use to convert a JSON string into a JSONObject. JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(stringJSON);
Try to get through this below example and each value contains space except integer one and giving this example just because of you don't have shared your source code. JSON File(personal_detail.json): { "name":"arif mustafa", "age":26, "address":["district is Korba","state is Chhattisgarh","country is India"] } Java source to read the JSON file format: import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class JSONExample { public static void main(String[] args) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader("src/resources/personal_detail.json")); JSONObject jsonObject = (JSONObject) obj; System.out.println(jsonObject + "\n"); String name = (String) jsonObject.get("name"); System.out.println("name : " + name); long age = (Long) jsonObject.get("age"); System.out.println("age : " + age); //get Object loop array JSONArray address = (JSONArray) jsonObject.get("address"); System.out.println("address is : "); Iterator<String> iterator = address.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } }
Append text field data to an existing JSON file in java
I have a text field where user can enter data, once data is received i want to append it to existing JSON file. I am able to read the existing data and getting the text field value, but while appending the new data with existing data I'm facing problem. Error: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 18 path $ Below code : JSON File : {"vins":[{"vin":"544554"},{"vin":"54554"}]} Text field value : String test ="3689"; so it should be appended as : {"vins":[{"vin":"544554"},{"vin":"54554"},{"vin":"3689"}]} Filereadwrite class : public class JSONFIlewrite { public static String Vinno_Read; public static List<String> linststring; public static void main(String[] args) { try { JSONParser parser = new JSONParser(); Object obj = parser.parse(new FileReader("C:\\Amaresh\\Test\\sample_json.json")); JSONObject jsonObject = (JSONObject) obj; System.out.println(jsonObject); linststring= new ArrayList(); // loop array JSONArray msg = (JSONArray) jsonObject.get("vins"); Iterator iterator = msg.iterator(); while (iterator.hasNext()) { Vinno_Read = iterator.next().toString(); linststring.add(Vinno_Read); } String list_string = ""; System.out.println(linststring); for(String temp:linststring){ list_string += temp; System.out.println("amar1"+list_string); } System.out.println("amar"+list_string); Vin vin4 = new Vin(); vin4.setVin("76354273462"); Vins vins = new Vins(); vins.addVins(vin4); Gson gson = new Gson(); //String jsonValue=list_string; String jsonValue = gson.toJson(list_string).toString(); System.out.println("json--"+jsonValue); Vins vins1 = gson.fromJson(jsonValue, Vins.class); System.out.println("ddd"+vins1); Vin vin = new Vin(); vin.setVin("544554"); vins1.addVins(vin); jsonValue = gson.toJson(vins1).toString(); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter("C:\\Amaresh\\Test\\sample_json.json")); writer.write(jsonValue); System.out.println("Test"+jsonValue); } catch (IOException e) { } finally { try { if (writer != null) writer.close(); } catch (IOException e) { } } } catch (Exception e) { e.printStackTrace(); } } } Setter Getter classes : public class Vin { #Expose private String vin; public String getVin() { return vin; } public void setVin(String vin) { this.vin = vin; } } public class Vins { #Expose List<Vin> vins = new ArrayList<>(); public List<Vin> getVins() { return vins; } public void addVins(Vin vin) { this.vins.add(vin); } }
Main Logic: you can see 4 blocks in the code Reading the json file and parsing to a java Object Casting de java Object to a JSonObject, parsing to a JsonArray and iterating the array printing the JsonElements Creating a new Vin Object and converting it to a JSON String using Gson.toJson method (2nd part is not required only illustrative purposes) Creating a JsonWriter, creating a Vins Object and loading it with the original JsonArray and then adding a new element (that correspondents to the new Vin Object created in step #3, finally writing the Vins Object to the [new] file. Input: {"vins":[{"vin":"544554"},{"vin":"54554"}]} Output: {"vins":[{"vin":"544554"},{"vin":"54554"},{"vin":"3689"}]} Code import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonWriter; public class JSONFIlewrite { public static String Vinno_Read; public static List<String> linststring; public static void main(String[] args) { try { JsonParser parser = new JsonParser(); Object obj = parser.parse(new FileReader("C:\\Amaresh\\Test\\sample_json.json")); JsonObject jsonObject = (JsonObject) obj; System.out.println(jsonObject); linststring = new ArrayList<String>(); // loop array JsonArray msg = (JsonArray) jsonObject.get("vins"); Iterator<JsonElement> iterator = msg.iterator(); while (iterator.hasNext()) { Vinno_Read = iterator.next().toString(); System.out.println("Vinno_Read---->" + Vinno_Read); } Vin newVin = new Vin(); newVin.setVin("3689"); Gson gson = new Gson(); String json = gson.toJson(newVin); System.out.println("json---->" + json); FileWriter file = new FileWriter("C:\\Amaresh\\Test\\sample_json2.json", false); JsonWriter jw = new JsonWriter(file); iterator = msg.iterator(); Vins vins = new Vins(); while (iterator.hasNext()) { vins.addVin(gson.fromJson(iterator.next().toString(), Vin.class)); } vins.addVin(newVin); gson.toJson(vins, Vins.class, jw); file.close(); } catch (Exception e) { e.printStackTrace(); } } } Notes: Since I don't know what library you are using, I have updated the class names to be compatible to GSON. I have also changed the method: public void addVins(Vin vin) in Vins Class to public void addVin(Vin vin)
To keep the existing content and append the new content to the end of JSON file: Example1: new FileWriter(file,true); or you can try example02: FileWriter file= new FileWriter(JSONLPATH,true)
How do I read from JSON File in Java? [duplicate]
This question already has answers here: How to parse JSON in Java (36 answers) Closed 7 years ago. I've read some other questions about this, but they did not seem to help me. As the title says, I want to know how to read from .json files using Java. Eg. I want my program to read a boolean value. (That is what I want it to.) I really hope you will be able to help me with this. I am able to use json-simple-1.1.1 if needed. What I've found so far (That did not work): String str = "Name"; JSONObject obj = new JSONObject(); String n = (String) obj.get("Name"); if (!n.equals("true")) { } else if (n.equals("true")) { ButtonsShow = true; } else if (n.equals("false")) { ButtonsShow = false; } Click to view the .Json file
you try it: import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class JsonSimpleExample { public static void main(String[] args) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader("c:\\test.json")); JSONObject jsonObject = (JSONObject) obj; String name = (String) jsonObject.get("name"); System.out.println(name); long age = (Long) jsonObject.get("age"); System.out.println(age); // loop array JSONArray msg = (JSONArray) jsonObject.get("messages"); Iterator<String> iterator = msg.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } }
error: non-static method get(Object) cannot be referenced from a static context
The code below shows: JavaApplication1.java:34: error: non-static method get(Object) cannot be referenced from a static context JSONArray cars = (JSONArray) JSONObject.get("cars"); import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class JavaApplication1 { #SuppressWarnings("unchecked") public static void main(String[] args) { JSONParser parser = new JSONParser(); try { JSONArray a = (JSONArray) parser.parse(new FileReader("C:/Users/Glambert/Dropbox/java/New folder/perfection/UPdate/json.txt")); for (Object o : a) { JSONObject person = (JSONObject) o; String name = (String) person.get("name"); System.out.println(name); String city = (String) person.get("city"); System.out.println(city); String job = (String) person.get("job"); System.out.println(job); JSONArray cars = (JSONArray) JSONObject.get("cars"); for (Object c : cars) { System.out.println(c+""); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } } Anyone has any idea why this is the case? (by the way, this code was found online and I edited it to test run, so that I can create a new code to take in a different kind of txt file.) Project: Code from StackOverflow page How to read json file into java with simple JSON library Code Author: https://stackoverflow.com/users/1212960/greg-kopff
Check this line JSONArray cars = (JSONArray) JSONObject.get("cars"); change it with JSONArray cars = (JSONArray) person.get("cars"); Issue was since you are calling the get method directly on the class.
Accessing JSON property name using java
I'm working on a way to parse JSON files and collect their contents for use elsewhere. I currently have a working example that is as follows: import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class testJSONParser { public static void main(String[] args) throws Exception { List<Map<String, String>> jsonArray = new ArrayList<Map<String, String>>(); BufferedReader br = new BufferedReader(new FileReader("json.txt")); try { String line = br.readLine(); while (line != null) { JSONObject jsonObject = (JSONObject)new JSONParser().parse(line); Map<String, String> currentLineMap = new HashMap<String, String>(); currentLineMap.put("country", jsonObject.get("country").toString()); currentLineMap.put("size", jsonObject.get("size").toString()); currentLineMap.put("capital", jsonObject.get("capital").toString()); jsonArray.add(currentLineMap); line = br.readLine(); } } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { br.close(); }; } } } I'm using the json simple library for parsing the passed in JSON strings. Here's a sample string from the parsed file. {"**country**":"Canada","**size**":"9,564,380","**capital**":"Ottawa"} What my question is about is how to take this code, and have the put method be able to assign to the corresponding Map dynamically. This is what I currently have: for (int i = 0; i < jsonObject.size(); i++) { currentLineMap.put(jsonObject.???.toString(), jsonObject.get(i).toString()); } The ??? part is where I'm stumped. Getting the values of the current JSON line is easy enough. But how to get the property values (highlighted in bold in the JSON string sample) eludes me. Is there a method that I can call on this object that I'm not familiar with? A different and better way to itenerate through this? Or am I doing this completely assbackwards right from the get go?
In the JSON.org reference implementation, you could do: for (String key : JSONObject.getNames(jsonObject)) { map.put(key, jsonObject.get(key)); } In JSON simple, you would do: for (Object keyObject : jsonObject.keySet()) { String key = (String)keyObject; map.put(key, (String)jsonObject.get(key)); } This should do the trick.