I'm trying to get a nested array from a json file, but I can't find a way to do it. What I want is a array with many other arrays. Using arr.toArray() I get a array with two strings one being "["user1", "name", "password"]" and "["user2", "name", "password"]". Is there a way to get an array with arrays?
{
"Users": {
"info": [
["user1", "name", "password"],
["user2", "name", "password"]
]
}
}
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("myPath"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonObject1 = (JSONObject) jsonObject.get("User1");
JSONArray arr = (JSONArray) jsonObject1.get("info");
System.out.println(arr.toArray());
} catch (Exception e) {
e.printStackTrace();
}
}
I think you might be using one of the older JSON Libraries, I believe its the org.json.simple library. If this is going to be an important project, I'd recommend switching over to the Google GSON Library.
For now, Try Switching
JSONObject jsonObject1 = (JSONObject) jsonObject.get("User1");
to
JSONObject jsonObject1 = (JSONObject) jsonObject.get("Users");
this should fix some of your problems. In your JSON file, Users is the object you need to get in order to access the info Array.
in the mean time, here's a starting place for GSON
GSON tutorialspoint
https://www.tutorialspoint.com/gson/gson_quick_guide.htm
Related
I have a goal to verify that certain JSON that I've got from RabbitMQ corresponds to one of expected JSONs in an array in a single file.
In other words, I need to verify that this JSON:
{
"networkCode":"network",
"programId":"92000"
}
is present in this JSON array:
[
{
"networkCode":"network",
"programId":"92000"
},
{
"networkCode":"network",
"programId":"92666"
}
]
Thank you very much for help!
Some part of my code
//GET DESIRABLE JSON
String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
JSONObject myJSON= new JSONObject(message);
//GET THE JSON ARRAYS FROM FILE
JSONParser parser = new JSONParser();
Object expectedJSONs= parser.parse(new FileReader("C:\\amqpclient\\src\\test\\java\\tradeDoubler\\ExpectedDTO.json"));
JSONArray expectedArray = (JSONArray) expectedJSONs;
JSONAssert.assertEquals(
myJSON, expectedArray , JSONCompareMode.LENIENT);
Compilation says that cannot resolve this
Exception in thread "main" java.lang.AssertionError: Expecting a JSON array, but passing in a JSON object
Org.json library is quite easy to use.
Example code below:
import org.json.*;
JSONObject obj = new JSONObject(" yourJSONObjectHere ");
JSONArray arr = obj.getJSONArray("networkArray");
for (int i = 0; i < arr.length(); i++)
{
String networkCode = arr.getJSONObject(i).getString("networkCode");
......
}
By iterating on your JSONArray, you can check if each object is equal to your search.
You may find more examples from: Parse JSON in Java
May I suggest you to use the Gson Library?
You can use something like this. But It will throw an exception if the json doesn't match/contains the fields.
Type listType = new TypeToken<ArrayList<YourJavaClassJsonModel>>() {
}.getType();
List<YourJavaClassJsonModel> resultList = gson.fromJson(JsonString, listType);
Hope it may help
You could use a JSON parser to convert the JSON to a Java object (Jackson and GSON are good options), and then check that object.
This is the JSON file I am working with
{"sentiment":
{"document":
{
"label": "positive",
"score": 0.53777
}
}
}
I need to access the value in label and score. using java. How can I do that?
Find below the code I am using right now:
JSONParser parser = new JSONParser();
try
{
Object object = parser
.parse(new FileReader("output_nlu_sentiment.json"));
//convert Object to JSONObject
JSONObject jsonObject = new JSONObject();
JSONObject sentimentobject= new JSONObject();
JSONObject documentobject = new JSONObject();
sentimentobject= (JSONObject) jsonObject.get("sentiment");
documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
//float score = (float) jsonObject.get("score");
System.out.println(label);
String test = (String) sentimentobject.get("label");
System.out.println(test);
} catch(FileNotFoundException fe)
{
fe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
Why is it printing the value as null.
You might want to have a look at JacksonXml for json parsing.
Right now the problem is that you're not using the JsonObject returned by parser.parse(...).
Instead you use the get method on objects you just created. This of course means that you don't getthe valie you want to.
Try to use following code (JSONObject jsonObject = (JSONObject) object instead of JSONObject jsonObject = new JSONObject();), because you didn't use object at all, just create new empty JSONObject.
JSONParser parser = new JSONParser();
try
{
Object object = parser
.parse(new FileReader("output_nlu_sentiment.json"));
//convert Object to JSONObject
JSONObject jsonObject = (JSONObject) object;
JSONObject sentimentobject = (JSONObject) jsonObject.get("sentiment");
JSONObject documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
System.out.println(label);
float score = (float) documentobject.get("score");
System.out.println(score );
}catch(FileNotFoundException fe)
{
fe.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
You have to make use of object created in Object object = parser.parse(new FileReader("output_nlu_sentiment.json")); while creating the jsonObject
For that you can look at the code below:
Object object = parser
.parse(new FileReader("file2.json"));
//convert Object to JSONObject
JSONObject jsonObject = (JSONObject) object;
JSONObject sentimentobject= new JSONObject();
JSONObject documentobject = new JSONObject();
sentimentobject= (JSONObject) jsonObject.get("sentiment");
documentobject= (JSONObject) sentimentobject.get("document");
String label = (String) documentobject.get("label");
//float score = (float) jsonObject.get("score");
System.out.println(label);
String test = (String) sentimentobject.get("label");
You will get the positive printed on console.
you should see the content in para 'sentimentobject',force convert into class JSONObject can not get the value you want.
I prefer the FasterXML Jackson support to parse JSON into plain old Java objects (POJOs). These POJOs are often called Data Transfer Objects (DTOs) and give you a way to turn your JSON fields into properly typed members of the corresponding DTO.
Here is an example method to do that. The ObjectMapper(s) are generally maintained as statics somewhere else because FasterXML's implementation caches information to improve efficiency of object mapping operations.
static final ObjectMapper mapper = new ObjectMapper();
This is the JSON deserialization method:
public static <T> T deserializeJSON(
final ObjectMapper mapper, final InputStream json,
final Class<T> clazz)
throws JsonParseException, UnrecognizedPropertyException,
JsonMappingException, IOException
{
final String sourceMethod = "deserializeJSON";
logger.entering(sourceClass, sourceMethod);
/*
* Use Jackson support to map the JSON into a POJO for us to process.
*/
T pojoClazz;
pojoClazz = mapper.readValue(json, clazz);
logger.exiting(sourceClass, sourceMethod);
return pojoClazz;
}
Assuming I have a class called FooDTO, which has the appropriate Jackson annotations/getters/setters (note you must always provide a default empty public constructor), you can do this:
FooDTO foo = deserializeJSON(mapper, inputstream, FooDTO.class);
The deserialization throws a few different exceptions (all of which have IOException as their parent class) that you will need to handle or throw back to the caller.
Here besides of the correction alreay addressed in comments and other answers, I include some other changes you can benefit of:
It is not necessary to initialize the JSONObjects with a new instance that is going to be ovewritten in the next line.
You can use getJSONObject(), getString(), getFloat() instead of get(), in this way you don't need to cast the result.
public void parseJson() {
JSONParser parser = new JSONParser();
try
{
JSONObject jsonObject = new JSONParser().parse(new FileReader("output_nlu_sentiment.json"));
JSONObject sentimentobject= null;
JSONObject documentobject = null;
sentimentobject= jsonObject.getJSONObject("sentiment");
documentobject= sentimentobject.getJSONObject("document");
String label = documentobject.getString("label");
float score = documentobject.getFloat("score");
String output = String.format("Label: %s Score: %f", label, score);
System.out.println(output);
}catch(FileNotFoundException fe){
fe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
Also for this kind of objects, where the attribute names could act as object properties, I suggest you take a look at Gson library. After modeling the json as a composition of POJOs, the parsing takes 1 line of code.
I`m trying to fetch some values fron a JSON file using:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("C:\\myfile.json"));
JSONArray array= new JSONArray();
array.add(obj);
If I run: System.out.println(array); , the output is
[{"flowrate":{"mod":0,"value":110},"command":{"cancel":0,"start":0}}]
, which is my json file.
My problem is how to get value from a specific field, let's say the value of "comand":"cancel".
I've tried JSONObject myitem = array.getJSONObject(1).getJSONObject("cancel"); with no success (error: getJSONObject(int) is undefined for the type JSONArray).
I mention that I'm using the json-simple toolkit.
I also could not validate your JSON. I made an assumption that you wanted to create an array of two objects (flowrate and command) and fixed the JSON:
String value = "[{\"flowrate\":{\"mod\":0,\"value\":110}},{\"command\":{\"cancel\":0,\"start\":0}}]";
JSONParser parser = new JSONParser();
Object obj = parser.parse(value);
JSONArray array=(JSONArray)obj;
JSONObject jo = (JSONObject) array.get(1);
System.out.println(jo.get("command"));
which gives the following output:
{"cancel":0,"start":0}
Process finished with exit code 0
After many hours of searching, I discovered that there is big difference between { } and [ ], therefore differnent methodes to parse them:
In my case:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("C:\\myfile.json"));
JSONObject jsonObject = (JSONObject) json;
JSONObject command= (JSONObject) jsonObject.get("command");
System.out.println("command: " + command);
long cancel= (Long) command.get("cancel");
System.out.println("cancel: " + cancel);
Here you'll find the best example for nested json objects
My JSON Structure will vary depend on the request. But the content inside each element remain same. For Example:
JSON1:
{
"h1": {
"s1":"s2"
},
"c1": {
"t1:""t2"
}
}
JSON2:
{
"h1": {
"s1":"s2"
},
"c2": {
"x1:""x2"
}
}
In the above example, elements inside h1,c1 and c2 are constant. Please let me know how to convert JSON to JAVA Object
Regards
Udhaya
First of all You need to understand Json Structure cause above format is incorrect visit this
and this
And you can use Google Gson or Json for parsing the result json String .
"t1:""t2" json format incorrect
Used
"t1":"t2"
Instead of
"t1:""t2"
and also used
"x1": "x2"
Instead of
"x1:""X2"
Code to take in java
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject jsonsubObject = jsonObject.getJSONObject("h1");
String s1 = jsonsubObject.getString("s2");
JSONObject jsonsubObject1 = jsonObject.getJSONObject("c1");
String t1 = jsonsubObject1 .getString("t2");
}
catch (JSONException e) {
e.printStackTrace();
}
Use Google Gson:
Gson gson = new Gson();
ClassName object;
try {
object = gson.fromJson(json, ClassName.class);
} catch (com.google.gson.JsonSyntaxException ex) {
//the json wasn't valid json
}
String validJson = gson.toJson(obj); //obj is an instance of any class
json must be a valid JSON String
import org.json.JSONObject;
you can simple pass your data in constructor of JSONObject it automatically handle, you need to throws JSONException which may occur during conversion id format of data is not correct
String data = "{'h1':{'s1':'s2'},'c1':{'t1:''t2'}}";
JSONObject jsnobject = new JSONObject(data);
I am using the JSON-simple library to parse the Json format. How can I append something to a JSONArray? For e.g. consider the following json
{
"a": "b"
"features": [{/*some complex object*/}, {/*some complex object*/}]
}
I need to append a new entry in the features.
I am trying to create a function like this:-
public void appendToList(JSONObject jsonObj, JSONObject toBeAppended){
JSONArray arr = (JSONArray)jsonObj.get("features");
//1) append the new feature
//2) update the jsonObj
}
How to achieve steps 1 & 2 in the above code?
You can try this:
public static void main(String[] args) throws ParseException {
String jsonString = "{\"a\": \"b\",\"features\": [{\"feature1\": \"value1\"}, {\"feature2\": \"value2\"}]}";
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(jsonString);
JSONObject newJSON = new JSONObject();
newJSON.put("feature3", "value3");
appendToList(jsonObj, newJSON);
System.out.println(jsonObj);
}
private static void appendToList(JSONObject jsonObj, JSONObject toBeAppended) {
JSONArray arr = (JSONArray) jsonObj.get("features");
arr.add(toBeAppended);
}
This will fulfill your both requirements.
Getting the array by: jsonObj["features"], then you can add new item by assign it as the last element in the array ( jsonObj["features"].length is the next free place to add new element)
jsonObj["features"][jsonObj["features"].length] = toBeAppended;
fiddle example