JSON parsing with Eclipse - java

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 :)

Related

JSON.simple - How to correctly access nested JSON objects

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"));
}
}
}

Get String value of json array in a json

For the below Json payload I'am trying to get the first array element of email_address.
However using the below code I get email address but with the array bracket and quotes like: ["test#test.com"].
I need only the email address text. First element array.
Payload:
{
"valid":{
"email_addresses":[
"testauto#test.com"
]
}
}
Code:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(jsonfilepath));
JSONObject jsonObjects = (JSONObject) parser.parse(jsonObject.get("valid").toString());
String email = jsonObjects.get("email_addresses").toString();
System.out.println("Email address:"+email);
Maybe this unitTest could help you
#Test
public void test() throws JSONException, FileNotFoundException {
JSONObject json = new JSONObject(new JSONTokener(new FileInputStream(new File(jsonfilepath))));
JSONObject valid = (JSONObject) json.get("valid");
Object emailAdresses = valid.get("email_addresses");
if (emailAdresses instanceof JSONArray) {
JSONArray emailAdressArray = (JSONArray) emailAdresses;
Object firstEmailAdress = emailAdressArray.get(0);
System.out.println(firstEmailAdress.toString());
}
}
You could use JSONArray to get the array values:
JSONArray emailAddresses = (JSONArray) jsonObjects.get("email_addresses");
String email = emailAddresses.getJSONObject(0).toString()
System.out.println("Email address: " + email);
Even though I strongly encourage using gson to parse json instead of doing this way, it makes life easier.

parsing and reading a json array java

have a structure for a contact book:
Contact { "Name":{ "First name":"Erm","Last Name": "Smith" }, "Number":67485647 }.
I save it as a Json object and than store it in a file with createContact().
public synchronized void createContact (String fname, String lname,String typeof, int number) throws FileNotFoundException
{
JsonObjectBuilder contactBuilder = Json.createObjectBuilder();
JsonObjectBuilder nameBuilder = Json.createObjectBuilder();
JsonArrayBuilder contactArrayBuilder= Json.createArrayBuilder();
nameBuilder.add("First Name",fname);
nameBuilder.add("Last Name",lname);
contactBuilder.add("Name", nameBuilder);
contactBuilder.add("Type", typeof);
contactBuilder.add("number", number);
JsonObject contact = contactBuilder.build();
contactArrayBuilder.add(contact);
JsonArray contactArray=contactArrayBuilder.build();
//write to file
OutputStream os = new FileOutputStream(filename);
JsonWriter fileWriter = Json.createWriter(os);
fileWriter.writeArray(contactArray);
fileWriter.close();
}
I read the file with:
InputStream is = new FileInputStream(filename);
JsonReader fileReader = Json.createReader(is);
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readObject());
JsonArrayBuilder contactArrayBuilder= Json.createArrayBuilder();
This is when I get the error
javax.json.JsonException: Cannot read JSON object, found JSON array
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:105)
I am using javax.json
The problem is that you are storing a JsonArray in that file, and then trying to read that JsonArray as a JsonObject. What you can do to get your code to work is remove these lines:
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readArray());
JsonArrayBuilder contactArrayBuilder= Json.createArrayBuilder();
and replace them with something like this:
JsonArray array = fileReader.readArray();
In the end, reading the file will look like this:
InputStream is = new FileInputStream(filename);
JsonReader fileReader = Json.createReader(is);
JsonArray array = fileReader.readArray();
Change this line
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readObject());
to this
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readArray());
as you are expecting an array but reading the object you are getting this error.

Java JSON/GSON - search all objects within an array and return match

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) {
}

Remove json object from json array

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);
}
}

Categories

Resources