How to read json file in java [duplicate] - java

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
I want to read Json file. My Json File has Content as follow
[
{
"arguments" : [
{
"IsEnabled" : "false",
"class" : "UITextField",
"width" : 238,
"parent" : {
"class" : "UIView",
"height" : 101,
"Y" : 192,
"width" : 280,
"X" : 20
},
"name" : "Enter UserName",
"X" : 40,
"isRightOf" : "NA",
"Recording Device" : "NA",
"Y" : 0
},
{
"data" : "Enter UserName",
"type" : "string"
}
],
}
]
I also tried GSON library to read JSON file.but fails . Please help

The JSON you provided is invalid (there is an invalid comma)
[
{
"arguments" : [
{
"IsEnabled" : "false",
"class" : "UITextField",
"width" : 238,
"parent" : {
"class" : "UIView",
"height" : 101,
"Y" : 192,
"width" : 280,
"X" : 20
},
"name" : "Enter UserName",
"X" : 40,
"isRightOf" : "NA",
"Recording Device" : "NA",
"Y" : 0
},
{
"data" : "Enter UserName",
"type" : "string"
}
], <-- this comma makes the json invalid
}
]

Your input json was wrong there is a comma missing as suggested.
Json objects are very hard to parse but if you once get the concept of how to parse the json data it is really easy.
You need to see if the property you are trying to access is a json array or an object. This is the basic rule if you are a beginner.
Here is the code::
OUTOUT IS::
arguments>>>>>>>>> [{"parent":{"width":280,"X":20,"Y":192,"class":"UIView","height":101},"Recording Device":"NA","IsEnabled":"false","width":238,"name":"Enter UserName","X":40,"isRightOf":"NA","Y":0,"class":"UITextField"},{"data":"Enter UserName","type":"string"}]
{"parent":{"width":280,"X":20,"Y":192,"class":"UIView","height":101},"Recording Device":"NA","IsEnabled":"false","width":238,"name":"Enter UserName","X":40,"isRightOf":"NA","Y":0,"class":"UITextField"}
{"data":"Enter UserName","type":"string"}
So, here in the code you can see that I have taken json array sometimes and object sometime, you need to differentiate between them.
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class test {
public static void main(String[] args) throws IOException, InterruptedException {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("test.json"));
JSONArray jsonObject = (JSONArray) obj;
JSONObject arr = (JSONObject) jsonObject.get(0);
JSONArray arguments = (JSONArray) arr.get("arguments");
System.out.println("arguments>>>>>>>>> "+arguments);
for(int i = 0 ; i< arguments.size() ;i++){
JSONObject object = (JSONObject) arguments.get(i);
System.out.println(object);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

how I can get data from JSONObject with Java?

I have an String called inputJson that contains
{"listPruebas": [
{
"nombrePrueba" : "pruebaA",
"id" : 1,
"tipoPrueba" : "PRUEBABASE1",
"elementoBase" : "tipoA",
"listaMarca": [
{
"elemento": "elemento1 ",
"tipo": "ABC",
"cadena": "SFSG34235WF32"
},
{
"elemento":"elemento2",
"tipo":"DEF",
"cadena":"DJRT64353GSDG"
},
{
"elemento" : "elemento3",
"formato ":"JPG"
}
]},
{
"nombrePrueba" : "pruebaB",
"id" : 2,
"tipoPrueba" : "PRUEBABASE2",
"elementoBase" : "imagenPrueba",
"listaMarca2": [
{
"elemento" : "imagen",
"tipo": "tipo5",
"cadena": "iVBORw0KGgoAAAANSUhEUgAAAgAAAA"
}
]
}
],
"listaBuscar":
[
{
"tipoBusqueda":"busqueda1",
"id" : 1,
"operacion" : "operacion1",
"valor" : "12"
},
{
"tipoBusqueda":"binario",
"id" : 2,
"operacion" : "operacion2",
"valor" : "13"
},
{
"tipoFiltro":"numerico",
"id" : 31,
"operacion" : "MENOR_QUE",
"valor" : "1980",
"intervalo" : 1
}
]
}
and I converted the String to JSONObject of this way
JSONObject object = new JSONObject(inputJson);
and I got this
jsonObject::{"listaBuscar":[{"valor":"12","id":1,"operacion":"operacion1","tipoBusqueda":"busqueda1"},{"valor":"13","id":2,"operacion":"operacion2","tipoBusqueda":"binario"},{"tipoFiltro":"numerico","intervalo":1,"valor":"1980","id":31,"operacion":"MENOR_QUE"}],"listPruebas":[{"listaMarca":[{"tipo":"ABC","elemento":"elemento1","cadena":"SFSG34235WF32"},{"tipo":"DEF","elemento":"elemento2","cadena":"DJRT64353GSDG"},{"elemento":"elemento3","formato":"JPG"}],"elementoBase":"tipoA","tipoPrueba":"PRUEBABASE1","nombrePrueba":"pruebaA","id":1},{"elementoBase":"imagenPrueba","tipoPrueba":"PRUEBABASE2","listaMarca2":[{"tipo":"tipo5","elemento":"imagen","cadena":"iVBORw0KGgoAAAANSUhEUgAAAgAAAA"}],"nombrePrueba":"pruebaB","id":2}]}
and now I need to extract information but I dont know how to do, for example I try this
object.getString("elemento1");
but I got this error
Caused by: org.json.JONException: JSONObject["elemento1"] not found
help me please
You can't get a nest JSON object from the top level. It's like a treemap. You need to convert it into a java object or get it level by level.
check this post, a lot of ways.
You json contains two json arrays, fetch them as -
JSONArray listaBuscArray = jsonObj.getJSONArray("listaBuscar");
JSONArray listPruebasArray = jsonObj.getJSONArray("listPruebas");
Now you can process and use them as -
for(int i=0; i<listaBuscArray.length; i++){
JSONObject obj = listaBuscArray.getJSONObject(i);
.... your logic
}

Remove JSON object with null value in object node tree

I have a JSON file from which I need to remove node objects which contain a data value of null. Can this be done? I'm using Jackson.
In the sample JSON below, I need to remove the object where its "v" tag has a null value.
Example:
{
"tags" : [ {
"tagId" : "G1.A_90LT1OUT",
"data" : [ {
"ts" : "2019-03-20T15:27:36",
"v" : "96.2427826",
"q" : "3"
} ]
}, {
"tagId" : "G1.A_90WN1OUT",
"data" : [ {
"ts" : "2019-03-20T15:27:36",
"v" : null,
"q" : "0"
} ]
}, {
"tagId" : "G1.A_90LT1OUT",
"data" : [ {
"ts" : "2019-03-20T15:29:20",
"v" : "96.2427826",
"q" : "3"
} ]
}, {
"tagId" : "G1.A_90WN1OUT",
"data" : [ {
"ts" : "2019-03-20T15:29:20",
"v" : null,
"q" : "0"
} ]
}, {
"tagId" : "G1.A_90LT1OUT",
"data" : [ {
"ts" : "2019-03-20T15:29:37",
"v" : "96.2581177",
"q" : "3"
} ]
}, {
"tagId" : "G1.A_90WN1OUT",
"data" : [ {
"ts" : "2019-03-20T15:29:37",
"v" : null,
"q" : "0"
} ]
} ]
}
I need it to look like this:
{
"tags" : [ {
"tagId" : "G1.A_90LT1OUT",
"data" : [ {
"ts" : "2019-03-20T15:27:36",
"v" : "96.2427826",
"q" : "3"
} ]
}, {
"tagId" : "G1.A_90LT1OUT",
"data" : [ {
"ts" : "2019-03-20T15:29:20",
"v" : "96.2427826",
"q" : "3"
} ]
}, {
"tagId" : "G1.A_90LT1OUT",
"data" : [ {
"ts" : "2019-03-20T15:29:37",
"v" : "96.2581177",
"q" : "3"
} ]
} ]
}
Can this be done? Please show me how. Fairly new to JSON manipulation, I've seen another post that kind of shows how to remove an element from a node, but I think my case is a little different. I've tried chasing down documentation to no avail, maybe looking in the wrong places.
Thank you in advance.
JSONPath
For JSON manipulation and filtering you can also use JsonPath library. It has a great web tool where you can try different filters and options. We can filter all nodes wit not null values using below path:
$.tags[?(#.data[0].v != null)]
Example application which does the same:
import com.jayway.jsonpath.JsonPath;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import java.io.File;
public class JsonPathApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
JSONArray filtered = JsonPath.parse(jsonFile).read("$.tags[?(#.data[0].v != null)]");
// Create root object
JSONObject root = new JSONObject();
root.appendField("tags", filtered);
// Get JSON
String json = root.toString();
// Write JSON on console or file
System.out.println(json);
}
}
Above code prints:
{"tags":[{"tagId":"G1.A_90LT1OUT","data":[{"ts":"2019-03-20T15:27:36","v":"96.2427826","q":"3"}]},{"tagId":"G1.A_90LT1OUT","data":[{"ts":"2019-03-20T15:29:20","v":"96.2427826","q":"3"}]},{"tagId":"G1.A_90LT1OUT","data":[{"ts":"2019-03-20T15:29:37","v":"96.2581177","q":"3"}]}]}
Jackson
The same with Jackson we can achieve in that way:
Read JSON as tree
Go to tags array
Iterate over array
For each item find v key in 0-index element
In case it is null - remove it
Example implementation:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(jsonFile);
ArrayNode tags = (ArrayNode) root.get("tags");
Iterator<JsonNode> elements = tags.elements();
while (elements.hasNext()) {
JsonNode item = elements.next();
ArrayNode data = (ArrayNode) item.get("data");
JsonNode v = data.get(0).get("v");
if (v.isNull()) {
elements.remove();
}
}
System.out.println(root);
}
}

How to fetch an array from a JSON String in Java? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
I have a JSON string as below which I am obtaining from a web service call. How can I retrieve the array from the builds key.
{
"actions" : [
{
},
null,
{
}
],
"description" : "Download Branch Build",
"displayName" : "EPIC-AUTODEV-8413",
"displayNameOrNull" : null,
"name" : "EPIC-AUTODEV-8413",
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/",
"buildable" : false,
"builds" : [
{
"number" : 71,
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/71/"
},
{
"number" : 70,
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/70/"
},
{
"number" : 69,
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/69/"
},
{
"number" : 68,
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/68/"
},
{
"number" : 67,
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/67/"
},
{
"number" : 66,
"url" : "http://localhost:80/jenkins/view/Branch-Builds/job/EPIC-AUTODEV-8413/66/"
},
}
I tried with tree=builds[*], but it gives me output like this
{"builds":[{},{},{},{},{},{},{},{},{},{},{}]}
try out javascript method JSON.parse, below is example
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
the above will give you object and than you refer part you want.
and if you want your object convert back in to json than try JSON.stringify()
var myJSON = JSON.stringify(obj);

Get value out JSON Object containing JSON arrays

How can I get the value of "distance" out of the following JSON object with java?
{
"destination_addresses" : [ "New York City, New York, Verenigde Staten" ],
"origin_addresses" : [ "Washington D.C., District of Columbia, Verenigde Staten" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "225 mijl",
"value" : 361714
},
"duration" : {
"text" : "3 uur 51 min.",
"value" : 13877
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I tried:
json.getJSONArray("rows").getJSONObject(0).getJSONObject("distance").toString();
But I always get org.json.JSONException: JSONObject["distance"] not found.
I think you are missing the second array "elements", you find array "row" so get object 0, in object 0 you need to find the "elements" array then take the object 0 again, so you can get the "distance" object.
Try this:
json.getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getJSONObject("distance").toString();
Again, I think. I hope this helped you.
Use java-json.jar
Convert JSON String to object and fetch the element.
You can refer this.
Try this:
package Sample;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class TestMain
{
public static void main(String[] args) throws JSONException
{
String s="{ \"destination_addresses\" : [ \"New York City, New York, Verenigde Staten\" ], \"origin_addresses\" : [ \"Washington D.C., District of Columbia, Verenigde Staten\" ], \"rows\" : [ { \"elements\" : [ { \"distance\" : { \"text\" : \"225 mijl\", \"value\" : 361714 }, \"duration\" : { \"text\" : \"3 uur 51 min.\", \"value\" : 13877 }, \"status\" : \"OK\" } ] } ], \"status\" : \"OK\"} ";
JSONObject jsonObj = new JSONObject(s);
JSONArray array= (JSONArray) jsonObj.get("rows");
JSONObject jsonObj2 =(JSONObject) array.get(0);
JSONArray array2= (JSONArray)jsonObj2.get("elements");
JSONObject jsonObj3 =(JSONObject) array2.get(0);
System.out.println(jsonObj3.get("distance"));
}
}
OUTPUT:
{"text":"225 mijl","value":361714}

jsonArray.length() not given the right number of array element

I am using org.json parser.
I am getting a json array using jsonObject.getJSONArray(key).
The problem is the jsonArray.length() is returning me 1 and my json array have 2 elements, what am I doing wrong?
String key= "contextResponses";
JSONObject jsonObject = new JSONObject(jsonInput);
Object value = jsonObject.get("contextResponses");
if (value instanceof JSONArray){
JSONArray jsonArray = (JSONArray) jsonObject.getJSONArray(key);
System.out.println("array length is: "+jsonArray.length());/*the result is 1! */
}
Here is my json:
{
"contextResponses" : [
{
"contextElement" : {
"type" : "ENTITY",
"isPattern" : "false",
"id" : "ENTITY3",
"attributes" : [
{
"name" : "ATTR1",
"type" : "float",
"value" : ""
}
]
},
"statusCode" : {
"code" : "200",
"reasonPhrase" : "OK"
}
}
]
}
The result is perfectly normal, since the JSONArray contains only one JSONObject. To get the length of the JSONObject you're looking for, use this:
// Get the number of keys stored within the first JSONObject of this JSONArray
jsonArray.getJSONObject(0).length();
//----------------------------
{
"contextResponses" : [
// The first & only JSONObject of this JSONArray
{
// 2 JSONObjects
"contextElement" : {
// 1
},
"statusCode" : {
// 2
}
}
]
}
Your array contains exactly one object therefore the length is correct:
"contextResponses" : [
{
... content of the object ...
}
]

Categories

Resources