I've a JsonArray like:
"fields" : [
{
"name":"First Name",
"id":1
},
{
"name":"Middle Name",
"id":2
},
{
"name":"Last Name",
"id":3
}
]
I want to remove second JsonObject from above JsonArray. In order to do that I' wrote following code:
JsonArray fieldsObject =jsonObject.getJsonArray("fields");
fieldsObject.remove(fieldsObject.getJsonObject(2));
But second line throws error: java.lang.UnsupportedOperationException
Is there any way, I can remove JsonObject from a JsonArray?
You can not remove element from JsonArray as it does not support remove() method:
private static final class JsonArrayImpl extends AbstractList<JsonValue> implements JsonArray {
And remove() method's implementation comes from AbstractList :
public E remove(int index) {
throw new UnsupportedOperationException();
}
Instead why don't you create a separate data strucure array or list to hold the objects that you want?
By the way, the purpose of using JsonArray is to load json data in object form that is why it supports read methods but does not support modifications on the loaded data structure.
May be Your JsonElement or JSONArray is null.
getJsonObject returns a JSONObject.
the remove method want int.
UnsupportedOperationException
if removing is not supported.
Try This :
JSONArray fieldsObject =jsonObject.getJsonArray("fields");
fieldsObject.remove(int index);
OR
JSONArray result = new JSONArray();
for(int i=0;i<fieldsObject.length();i++)
{
if(i!=2)
{
result.put(fieldsObject.get(i));
}
}
and assign result to original one
fieldsObject=result;
gson library
Remove works for gson library version 2.3.1
public static void main(String[] args) throws Exception {
String s = "{ \"fields\" : [ "+
" {\"name\":\"First Name\",\"id\":1},"+
"{\"name\":\"Middle Name\",\"id\":2},"+
"{\"name\":\"Last Name\",\"id\":3}"+
"]}";
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(s).getAsJsonObject();
System.out.println("original object:"+json);
JsonArray fieldsObject = json.getAsJsonArray("fields");
System.out.println("Before removal :"+fieldsObject);
Object remove = fieldsObject.remove(1);
System.out.println("After removal :"+fieldsObject);
}
Output:
original object:{"fields":[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]}
Before removal :[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]
After removal :[{"name":"First Name","id":1},{"name":"Last Name","id":3}]
org.json library
Remove works for org.json library
public static void main(String[] args) throws Exception {
String s = "{ \"fields\" : [ "+
" {\"name\":\"First Name\",\"id\":1},"+
"{\"name\":\"Middle Name\",\"id\":2},"+
"{\"name\":\"Last Name\",\"id\":3}"+
"]}";
JSONObject json = new JSONObject(s);
System.out.println("original object:"+json);
JSONArray fieldsObject =json.getJSONArray("fields");
System.out.println("Before removal :"+fieldsObject);
Object remove = fieldsObject.remove(1);
System.out.println("After removal :"+fieldsObject);
}
Output:
original object:{"fields":[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]}
Before removal :[{"name":"First Name","id":1},{"name":"Middle Name","id":2},{"name":"Last Name","id":3}]
After removal :[{"name":"First Name","id":1},{"name":"Last Name","id":3}]
I tried using org.json library as mentioned by Sanj in the above post. We can remove the element from JSONArray as below. I placed the json content in the .txt file and read into the String object for constructing the JSONObject. Please refer the code below.
public class App{
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("json.txt"));
String jsonContent = "";
String jsonLine;
while((jsonLine=br.readLine())!=null){
jsonContent+=jsonLine;
}
JSONObject jObj = new JSONObject(jsonContent);
JSONArray jsonArray = jObj.getJSONArray("fields");
jsonArray.remove(1);
System.out.println(jsonArray);
}
}
Related
Example of my json file is
{
"collection": [
{
"trophy-name": {
"text": "swimming",
"text2": "fast swimming"
},
"length": "50m",
"pool": "outside",
"weather": "20"
}
]
}
Right now I am able to get values from lenght, pool and weather. But I am stuck on how to access the nested array nested object trophy-name.
My code is:
public class main {
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException
{
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); // json path
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("collection");
for (Object number : array )
{
JSONObject testObj = (JSONObject) number;
String pool = (String)testObj.get("pool");
System.out.println(testObj.get("length"));
System.out.println(pool);
System.out.println(testObj.get("weather"));
}
}
}
This is my first time experimenting with json files so I am trying to play around with it so the code is not great.
I probably have to create new object like
JSONObject trophyObj = (JSONObject) jsonObject.get("trophy-name");
And then from there I should be able to get the text with this?
String troph = (String) trophyObj.get("text");
Even if I that is correct I am not sure how to implement it into the loop or if there is better way to do the loop?
Dont mind redoing the code differently and any advice appreciated.
Yes, you are right, simply extract the JSONObject within the loop and then get the required fields.
public class main {
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException
{
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); // json path
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("collection");
for (Object number : array )
{
JSONObject testObj = (JSONObject) number;
String pool = (String)testObj.get("pool");
System.out.println(testObj.get("length"));
System.out.println(pool);
System.out.println(testObj.get("weather"));
JSONObject trophyObj = (JSONObject) testObj.get("trophy-name");
System.out.println((String)trophyObj.get("text"));
System.out.println((String)trophyObj.get("text2"));
}
}
}
Hi i have simply problem, but i can find solution. If somebody can show to me solution.
...
(Unirest) HttpResponse<String> paluuREST = AbaXapi.HttpResponse(aString);
enter bring outside to me long Json Array:
So i put this inside Arraylist and short diffrent values...
"{\"body\":[{\"id\":\"1bc4aa42-1ef9-11e7-b023-97a5ff9c3a97\",\"name\":\"DFB-572\",\"imei\":13226005525791,\"vehicle_params\":{\"vin\":null,\"make\":null,\"model\":null,\"plate_number\":null}}]}"
Here is java code:
JSONObject jsonObject = new JSONObject(paluuREST);
System.out.println(jsonObject);
JSONArray jsonArray = jsonObject.getJSONArray("body");
ArrayList<Object> listdata = new ArrayList<Object>();
for (int i=0;i<jsonArray.length();i++){
//Adding each element of JSON array into ArrayList
listdata.add(jsonArray.get(i));
}
System.out.println("Each element of ArrayList");
for(int i=0; i<listdata.size(); i++) {
//Printing each element of ArrayList
System.out.println(listdata.get(i));
}
Error Message:
Exception in thread "main" org.json.JSONException: JSONObject["body"] is not a JSONArray.
at org.json.JSONObject.wrongValueFormatException(JSONObject.java:2628)
So how can be? How i need to change code, thanks for your help.
Please be more carefull in the formulation of the question, if everything is brought to the right, then there are no problems.
public static void main(String[] args) throws Exception {
String s = "{\"body\":[{\"id\":\"1bc4aa42-1ef9-11e7-b023-97a5ff9c3a97\",\"name\":\"DFB-572\",\"imei\":13226005525791,\"vehicle_params\":{\"vin\":null,\"make\":null,\"model\":null,\"plate_number\":null}}]}";
JSONObject obj = new JSONObject(s);
JSONArray body = obj.getJSONArray("body");
System.out.println(body);
ArrayList<Object> objects = new ArrayList<>();
for (Object o : body) {
objects.add(o);
}
System.out.println("objects = " + objects);
}
used org.json lib
I am working on JSON files to compare their data. I only want to check if value of 1 json is same as of 2nd json file.
both are having same key names and order.
JSON file data looks like :
{ "ab_property": [
{
"name": "abc",
"value": "1"
},
I have solve your problem.Also you can direct match value using key instead of for loop.
import java.io.FileReader;
import java.util.Set;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class compareJsonFile {
public static void main(String[] args) throws Exception {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("/home/chandrakant/Desktop/json1.json"));
Object obj1 = parser.parse(new FileReader("/home/chandrakant/Desktop/json2.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonObject1 = (JSONObject) obj1;
Set<String> s = jsonObject.keySet();
for (String str : s) {
System.out.println("key:" + str + " : value1:" + jsonObject.get(str) + ":value2:" + jsonObject1.get(str));
//compare value of json1 with json2
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
If something miss, please comment me.
JSONassert is a popular library to compare JSON objects. If the two files are identical (keys and values), it fits your use case.
An example using org.apache.commons.io.IOUtils to read the files:
String expected = IOUtils.toString(new File("/path/to/expected").toURI(), Charset.defaultCharset()));
String actual = IOUtils.toString(new File("/path/to/actual").toURI(), Charset.defaultCharset()));
JSONAssert.assertEquals(expected, actual, false);
I am returning an JSON array which contains many objects, I'm looking to be able to search the attributes in each object and then return the objects that meet this criteria.
I am able to return the JSON array but I'm having trouble on how to then search through the objects to match the attribute values to a given value.
Some example values from the array:
[
{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483384640123117E9,"uID":"136199_3_10"},
{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483379834470379E9,"uID":"136199_3_10"},
{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483384639621985E9,"uID":"136199_3_10"}
]
I'm using the following code to return the array, which works as expected:
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonArray rootArr = root.getAsJsonArray();
The following block of code is what I'm using to search through an object for the given attribute value, this code works when only an object is returned but gives an error when the whole array is returned:
JsonObject rootObj = rootArr.getAsJsonObject();
for (String attribute : attributes) {
System.out.println(rootObj.get(attribute).getAsString());
}
It is giving the error:
java.lang.IllegalStateException: Not a JSON Object:
I've tried changing rootObj.get(attribute) to rootArr.get(attribute) but that returns the error:
incompatible types: java.lang.String cannot be converted to int
This is the method call:
method("136199", Arrays.asList("blobJson", "deviceMfg", "uID"));
Method declaration:
void method(String sensor, List<String> attributes)
The issue is that you're trying to treat JsonArray to JsonObject. Try the below code and see if it works for you. Point of interest for now is - JsonObject rootObj = rootArr.get(0).getAsJsonObject();
public static void main(String[] args) {
String json = "[{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483384640123117E9,\"uID\":\"136199_3_10\"},{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483379834470379E9,\"uID\":\"136199_3_10\"},{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483384639621985E9,\"uID\":\"136199_3_10\"}]";
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(json);
JsonArray rootArr = root.getAsJsonArray();
JsonObject rootObj = rootArr.get(0).getAsJsonObject();
rootObj.entrySet().forEach(entry -> System.out.println(entry.getKey()+": "+entry.getValue().getAsString()));
}
Here is what you can try
try {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
Log.e("JSON Count", jsonArray.get(i).toString());
}
} catch (Exception e) {
}
I'm new in java and i have this maybe simple faculty project. I must to parse json with eclipse, so i started but without any success. I don't know how to start when i have a multiple object in json.
I started like this:
public static void main(String[] args) {
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray objectArray = jsonObject.getJSONArray("product");
//JSONObject site= jsonSites.getJSONObject(1);
long elementaryProductId = (long) jsonObject[0].get("elementaryProductId");
System.out.println("The id is: " + elementaryProductId);'
And thi is my json file:
[{
"elementaryProductId":1,
"bonusMalus":30,
"deductible":500,
"comprehensive":1,
"partial":0,
"legacyPremium":130,
"product":{
"productId":2,
"garage":"true",
"constructionYear":1990,
"region":"East",
"dateOfBirthYoungest":"1983-06-22",
"objectValue":25000,
"type":"Car",
"insuredObject":{
"name":"Car",
"ownersName":"Jovana",
"mileage":300000,
"engineCapacity":120
},
"salesProduct":{
"salesProductId":3,
"currency":"EUR",
"contractStart":"2011-01-01",
"contractEnd":"2012-01-01"
},
"productType":"Car"
}
},
{
"elementaryProductId":1,
"bonusMalus":5,
"deductible":100,
"comprehensive":1,
"partial":0,
"legacyPremium":75.38,
"product":{
"productId":2,
"garage":"true",
"constructionYear":2005,
"region":"East",
"dateOfBirthYoungest":"1999-06-22",
"objectValue":30000,
"type":"Car",
"insuredObject":{
"name":"Car",
"ownersName":"Jelena",
"mileage":300000,
"engineCapacity":210
},
"salesProduct":{
"salesProductId":3,
"currency":"EUR",
"contractStart":"2013-01-01",
"contractEnd":"2014-01-01"
},
"productType":"Car"
}
}]
I got it to work with the following:
public static void main(String[] args) throws IOException, ParseException{
FileReader reader = new FileReader(new File("filename.json"));
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
JSONObject object = (JSONObject) jsonArray.get(0);
long elementaryProductId = (Long) object.get("elementaryProductId");
System.out.println("The id is: " + elementaryProductId);
}
Explanation of the above:
You know the outermost element is an array so parse straight into a JSONArray. Next you want to pull out the first element of that array which is a JSONObject (its in braces). After that the code should be fairly self explanatory :)