How do I parse JSON objects from a JSONArray? - java

I have a very large JSON file in the following format:
[{"fullname": "name1", "id": "123"}, {"fullname": "name2", "id": "245"}, {"fullname": "name3", "id": "256"}]
It looks like a JSONArray. All the records are written in the same line.
Can you help me how can I parse this file using Java. I want to read each JSON object and display all the fullname and ids. Below is my attempt, but my code is not working:
import org.apache.commons.lang3.StringEscapeUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JSONFileReaderDriver {
public static void main(String[] args) throws FileNotFoundException,
IOException, ParseException
{
String filename="Aarau";
String src="C:\\"+filename+".json";
JSONParser parser = new JSONParser();
JSONObject obj;
try
{
BufferedReader br=new BufferedReader (new FileReader(src));
obj = (JSONObject) new JSONParser().parse(row);
String fullname=obj.get("fullname");
String id=obj.get("id");
System.out.println ("fullname: "+fullname+" id: "+id);
}catch(Exception e)
{e.printStackTrace();}
br.close();
}
}

Make your life easy and use an ObjectMapper.
This way you simply define a Pojo with the same properties as you json object.
In you case you need a Pojo that looks like this:
public class Person{
private String fullname;
private int id;
public Person(String fullname, int id) {
this.fullname = fullname;
this.id = id;
}
public String getFullname() {
return fullname;
}
public int getId() {
return id;
}
}
With that you only need to do:
ObjectMapper objectMapper = new ObjectMapper();
List<Person> persons = objectMapper.readValue(myInputStream, TypeFactory.defaultInstance().constructCollectionType(List.class, Person.class));
This is a hassle free and type safe approach.
Dependencies needed:
https://github.com/FasterXML/jackson-databind
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

you can use Json.simple java api , below is code that can helpful to you
byte[] bFile = Files.readAllBytes(new File("C:/xyz.json").toPath());
JSONArray root = (JSONArray) JSONValue.parseWithException(bFile);
JSONObject rootObj = (JSONObject) root.get(0);
You can get values from JSONObject based on key , it also depends on format of your json as there could be nested json data. So you have to extract data accordingly . Apart from this you can use jackson parser api or GSON as well.

Okay folks...just solved my problem. I am posting the solution in case someone runs into the same issue again, can use my solution. My solution is partly motivated by Rahul Rabhadiya. Thanks, dude.
try{
row=br.readLine();
JSONArray root = (JSONArray) JSONValue.parseWithException(row);
for (int i=0;i<root.size();i++)
{
JSONObject rootObj = (JSONObject) root.get(i);
String fullname=(String) rootObj.get("fullname");
System.out.println (fullname);
}
}catch(Exception e)
{
e.printStackTrace();
}

Your json is a JSONArray, so when you are parsing it, you need to parse it as a JSONArray.
JSONParser jsonParser = new JSONParser();
JSONArray a = (JSONArray) jsonParser.parse(new FileReader(src));
for (Object o : a) {
// access your object here.
}

I would suggest going with Jackson, in particular the Jackson Streaming API which is perfect for parsing large arrays like this.
See this answer: https://stackoverflow.com/a/24838392/3765428

Related

How can I use JsonParser (javax.json.stream.JsonParser) twice

I need to use a JsonParser twice, once to validate the format of my JsonStream by the json schema given..., then I need to contruct my object 'Product'.
The problem is that if I use the parser once, I cannot re-use it a second time. It's like it loses its data values .
Here is my Original code where I construct my Product object using the parser.. :
import javax.json.bind.serializer.DeserializationContext;
import javax.json.bind.serializer.JsonbDeserializer;
import javax.json.stream.JsonParser;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class ProductDeserializer implements JsonbDeserializer<Product>
{
#Override
public Product deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType)
{
Product product = new Product();
while (parser.hasNext())
{
JsonParser.Event event = parser.next();
if (event == JsonParser.Event.KEY_NAME && parser.getString().equals("productNumber"))
{
parser.next();
product.setProductNumber(parser.getString());
This works fine But I need to include this validation of the json format first..:
ObjectMapper objectMapper = new ObjectMapper();
JsonSchemaFactory schemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V201909);
String schemaStream = "My json schema here..";
JsonNode json = null;
try
{
json = objectMapper.readTree(parser.getObject().toString());
}
catch (JsonProcessingException eParam)
{
eParam.printStackTrace();
}
JsonSchema schema = schemaFactory.getSchema(schemaStream);
Set<ValidationMessage> validationResult = schema.validate(json);
if (validationResult.isEmpty()) {
System.out.println("no validation errors ");
} else {
System.out.println("There are validation errors ");
}
So if I try to include this part then the contruction of my Product Object will not work anymore and the Product will be null..
So my question is how can I use the parser twice in the same method ..
Thanks a lot in advance..

Read JSON file with JSONParser not available in the jarfile

I am trying to read a json file and convert it to the jsonObject and when I searched on how to do it, I came across the method to user
JSONParser parser= new JSONParse();
But the version of org.json I am using in the code is "20180803". It does not contain JSONParser. Has it been removed from the org.json package? If so what is the new class or method that I could use to read a json file and convert it to a json object.
My dependency is given below :
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</dependency>
Hi you can use simple JSON. You just need to add in your pom.xml file:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>
Sample code
public static JSONObject convertJsonStingToJson(String jsonString) {
JSONParser parser = new JSONParser();
return json = (JSONObject) parser.parse(jsonString);
}
org.json library has very simple API which does not have JSONParser but has JSONTokener. We can construct JSONObject or JSONArray directly from String:
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonApp {
public static void main(String[] args) {
// JSON Object
String object = "{\"p1\":\"v1\", \"p2\":2}";
JSONObject jsonObject = new JSONObject(object);
System.out.println(jsonObject);
// JSON Array
String array = "[{\"p1\":\"v1\", \"p2\":2}]";
JSONArray jsonArray = new JSONArray(array);
System.out.println(jsonArray);
}
}
Above code prints:
{"p1":"v1", "p2":2}
[{"p1":"v1","p2":2}]
You need to notice that it depends from JSON payload which class to use: if JSON starts from { use JSONObject, if from [ - use JSONArray. In other case JSON payload is invalid.
As it mentioned in other answers, if you can you should definitely use Jackson or Gson
Add following dependency in build file
//json processing
implementation("com.fasterxml.jackson.core:jackson-core:2.9.8")
implementation("com.fasterxml.jackson.core:jackson-annotations:2.9.8")
implementation("com.fasterxml.jackson.core:jackson-databind:2.9.8")
a.json file
{
"a": "b"
}
code:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.FileInputStream;
import java.io.InputStream;
public class App {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
InputStream input = new FileInputStream("a.json");
JsonNode obj = objectMapper.readTree(input);
System.out.println(obj.get("a")); // "b"
}
}
The short answer to your question is: No, it was not removed, because it never existed.
I think you are mentioning a library, and trying to use another one. Anyway, if you really want to use org.json, you can find how here
JSONObject jsonObject = new JSONObject(instanceOfClass1);
String myJson = jsonObject.toString();

How to drop keys from string json in java?

I have a json string like this:
{"a":"vala", "b":"valb", "c":"valc"}
I want to convert the above string to a JSONObject so that I can do something like:
testObject.remove("b");
testObject.remove("c");
So that I can easily print out the json string of:
{"a":"vala"}
What is the simplest way for me to do this?
org-json-java can do the things you want
import org.json.JSONException;
import org.json.JSONObject;
public class JsonTest {
public static void main(String[] args) {
try {
JSONObject testObject = new JSONObject("{\"a\":\"vala\", \"b\":\"valb\", \"c\":\"valc\"}");
testObject.remove("b");
testObject.remove("c");
System.out.println(testObject.toString()); // This prints out the json string
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The execution result is
{"a":"vala"}
Make sure you've downloaded and imported org.json-YYYYMMDD.jar from here before you run the above code.
Firstly I think you need change title of question.
Secondly, If you want change from String to Json just using org.json library
JSONObject jsonObj = new JSONObject("{\"a\":\"valuea\",\"b\":\"valueb\"}");
Are you tried remove. http://www.json.org/javadoc/org/json/JSONObject.html#remove(java.lang.String)
Json.remove(key)

String to json conversion issue

I am trying to convert a string to JSONObject object using the below code,but i am getting
Exception in thread "main" java.lang.ClassCastException:
org.json.simple.JSONObject cannot be cast to net.sf.json.JSONObject .
Source:
import net.sf.json.JSONObject;
import org.json.simple.parser.JSONParser;
public static void run(JSONObject jsonObject) {
System.out.println("in run--");
}
public static void main(String[] args) throws Exception {
System.out.println("here");
String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}";
JSONObject jsonObj;
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
jsonObj = (JSONObject) obj;
run(jsonObj);
}
What is wrong here?
You've imported JSONObject from the wrong package. Change this line:
import net.sf.json.JSONObject;
to this:
import org.json.simple.JSONObject;
Implementing the following solution, You don't even have to bother about a parser...
The Problem here is that u're trying to cast a object of type org.json.simple.JSONObject to net.sf.json.JSONObject. You might wanna try The package org.codehaus.jettison.json.JSONObject. that is enough to do all the required things.
Simple Example:
First, Prepare a String:
String jStr = "{\"name\":\"Fred\",\"Age\":27}";
Now, to parse the String Object, U just have to pass the String to the JSONObject(); constructor method
JSONObject jObj = new JSONObject(jStr);
That should do it and voila! You have a JSONObject.
Now you can play with it as u please.
How So Simple ain't it?
The Modified version of the Code might look like:
import net.sf.json.JSONObject;
import org.codehaus.jettison.json.JSONObject;
public static void run(JSONObject jsonObject) {
System.out.println("in run-- "+jsonObject.getInt("person_id"));
}
public static void main(String[] args) throws Exception {
System.out.println("here");
String json = "{\"task\": \"com.ge.dbt.workers.surveytoexcel.worker.SurveyWorker\",\"prod_id\": 12345,\"survey_id\": 5666,\"person_id\": 18576567,\"req_date\": \"12\12\2012\"}";
JSONObject jsonObj = new JSONObject(json);
run(jsonObj);
}
with JSON, It's SssOooooooo simple

Convert JSON to Map

What is the best way to convert a JSON code as this:
{
"data" :
{
"field1" : "value1",
"field2" : "value2"
}
}
in a Java Map in which one the keys are (field1, field2) and the values for those fields are (value1, value2).
Any ideas? Should I use Json-lib for that? Or better if I write my own parser?
I hope you were joking about writing your own parser. :-)
For such a simple mapping, most tools from http://json.org (section java) would work.
For one of them (Jackson https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator), you'd do:
Map<String,Object> result =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
(where JSON_SOURCE is a File, input stream, reader, or json content String)
Using the GSON library:
import com.google.gson.Gson;
import com.google.common.reflect.TypeToken;
import java.lang.reclect.Type;
Use the following code:
Type mapType = new TypeToken<Map<String, Map>>(){}.getType();
Map<String, String[]> son = new Gson().fromJson(easyString, mapType);
I like google gson library.
When you don't know structure of json. You can use
JsonElement root = new JsonParser().parse(jsonString);
and then you can work with json. e.g. how to get "value1" from your gson:
String value1 = root.getAsJsonObject().get("data").getAsJsonObject().get("field1").getAsString();
Use JSON lib E.g. http://www.json.org/java/
// Assume you have a Map<String, String> in JSONObject jdata
#SuppressWarnings("unchecked")
Iterator<String> nameItr = jdata.keys();
Map<String, String> outMap = new HashMap<String, String>();
while(nameItr.hasNext()) {
String name = nameItr.next();
outMap.put(name, jdata.getString(name));
}
My post could be helpful for others, so imagine you have a map with a specific object in values, something like that:
{
"shopping_list":{
"996386":{
"id":996386,
"label":"My 1st shopping list",
"current":true,
"nb_reference":6
},
"888540":{
"id":888540,
"label":"My 2nd shopping list",
"current":false,
"nb_reference":2
}
}
}
To parse this JSON file with GSON library, it's easy :
if your project is mavenized
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
Then use this snippet :
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
//Read the JSON file
JsonElement root = new JsonParser().parse(new FileReader("/path/to/the/json/file/in/your/file/system.json"));
//Get the content of the first map
JsonObject object = root.getAsJsonObject().get("shopping_list").getAsJsonObject();
//Iterate over this map
Gson gson = new Gson();
for (Entry<String, JsonElement> entry : object.entrySet()) {
ShoppingList shoppingList = gson.fromJson(entry.getValue(), ShoppingList.class);
System.out.println(shoppingList.getLabel());
}
The corresponding POJO should be something like that :
public class ShoppingList {
int id;
String label;
boolean current;
int nb_reference;
//Setters & Getters !!!!!
}
Hope it helps !
With google's Gson 2.7 (probably earlier versions too, but I tested 2.7) it's as simple as:
Map map = gson.fromJson(json, Map.class);
Which returns a Map of type class com.google.gson.internal.LinkedTreeMap and works recursively on nested objects.
This way its works like a Map...
JSONObject fieldsJson = new JSONObject(json);
String value = fieldsJson.getString(key);
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.1</version>
</dependency>
I do it this way. It's Simple.
import java.util.Map;
import org.json.JSONObject;
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
JSONObject jsonObj = new JSONObject("{ \"f1\":\"v1\"}");
#SuppressWarnings("unchecked")
Map<String, String> map = new Gson().fromJson(jsonObj.toString(),Map.class);
System.out.println(map);
}
}
java.lang.reflect.Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Gson gson = new Gson();
Map<String, Object> categoryicons = gson.fromJson(json, mapType );
If you're using org.json, JSONObject has a method toMap().
You can easily do:
Map<String, Object> myMap = myJsonObject.toMap();
The JsonTools library is very complete. It can be found at Github.
Try this code:
public static Map<String, Object> convertJsonIntoMap(String jsonFile) {
Map<String, Object> map = new HashMap<>();
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.readValue(jsonFile, new TypeReference<Map<String, Object>>() {
});
map = mapper.readValue(jsonFile, new TypeReference<Map<String, String>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
One more alternative is json-simple which can be found in Maven Central:
(JSONObject)JSONValue.parse(someString); //JSONObject is actually a Map.
The artifact is 24kbytes, doesn't have other runtime dependencies.
If you need pure Java without any dependencies, you can use build in Nashorn API from Java 8. It is deprecated in Java 11.
This is working for me:
...
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
...
public class JsonUtils {
public static Map parseJSON(String json) throws ScriptException {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine engine = sem.getEngineByName("javascript");
String script = "Java.asJSONCompatible(" + json + ")";
Object result = engine.eval(script);
return (Map) result;
}
}
Sample usage
JSON:
{
"data":[
{"id":1,"username":"bruce"},
{"id":2,"username":"clark"},
{"id":3,"username":"diana"}
]
}
Code:
...
import jdk.nashorn.internal.runtime.JSONListAdapter;
...
public static List<String> getUsernamesFromJson(Map json) {
List<String> result = new LinkedList<>();
JSONListAdapter data = (JSONListAdapter) json.get("data");
for(Object obj : data) {
Map map = (Map) obj;
result.add((String) map.get("username"));
}
return result;
}
JSON to Map always gonna be a string/object data type. i have GSON lib from google.
Gson library working with string not for complex objects you need to do something else
Try this piece of code, it worked for me,
Map<String, Object> retMap = new Gson().fromJson(
myJsonString, new TypeToken<HashMap<String, Object>>() {}.getType()
);
import net.sf.json.JSONObject
JSONObject.fromObject(yourJsonString).toMap
Underscore-java library can convert json string to hash map. I am the maintainer of the project.
Code example:
import com.github.underscore.U;
import java.util.*;
public class Main {
#SuppressWarnings("unchecked")
public static void main(String[] args) {
String json = "{"
+ " \"data\" :"
+ " {"
+ " \"field1\" : \"value1\","
+ " \"field2\" : \"value2\""
+ " }"
+ "}";
Map<String, Object> data = (Map) U.get((Map<String, Object>) U.fromJson(json), "data");
System.out.println(data);
// {field1=value1, field2=value2}
}
}
JSON to Map always gonna be a string/object data type. i haved GSON lib from google.
works very well and JDK 1.5 is the min requirement.

Categories

Resources