Convert string to json doesn't work java - java

I have a problem with convert string to json.
Namely, my json string is:
{"serverId":2,"deviceId":736,"analysisDate":"2017-05-11T07:20:27.713Z","eventType":"Logs","eventAttributes":[{"name":"level","value":"INFO"},{"name":"type","value":"Video Blocked On"},{"name":"cameraId","value":"722"},{"name":"userId","value":"1"}]}
My code:
try {
JSONObject object = new JSONObject(jsonString);
JSONArray array = object.getJSONArray("eventAttributes");
System.out.println("ARRAY: " + array);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = new JSONObject(array.getJSONObject(i));
System.out.println("OBJ: " + obj);
}
} catch (JSONException ex) {
Exceptions.printStackTrace(ex);
}
System.out.println array is:
[{"name":"level","value":"INFO"},{"name":"type","value":"Video Blocked On"},{"name":"cameraId","value":"722"},{"name":"userId","value":"1"}]
but if I print obj is "{}", four times. So it is correct, because array has 4 elements, but why it is empty object? I'm using org.json.
Thanks

array.getJSONObject(i) is already returning you an object of type JSONObject you dont need to pass it to constructor of JSONObject class.
simply write
...
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
System.out.println("OBJ: " + obj);
}
...

You're calling the JSONObject(Object) constructor, passing in a JSONObject (the element in the array). That constructor is documented as:
Construct a JSONObject from an Object using bean getters. It reflects on
all of the public methods of the object. For each of the methods with no
parameters and a name starting with "get" or
"is" followed by an uppercase letter, the method is invoked,
and a key and the value returned from the getter method are put into the
new JSONObject. [...]
Now JSONObject itself doesn't have anything that fits a bean getter, so you end up with no keys. You don't want to treat the JSONObject as a bean.
That's why your current code doesn't work. To fix it, just don't call the constructor - instead, use the fact that the array element is already a JSONObject:
JSONObject obj = array.getJSONObject(i);
Output with that change:
OBJ: {"name":"level","value":"INFO"}
OBJ: {"name":"type","value":"Video Blocked On"}
OBJ: {"name":"cameraId","value":"722"}
OBJ: {"name":"userId","value":"1"}

If you consider following example you can do it in 3 ways :
jsonString = {
"name" : "John",
"sport" : "Soccer",
"age" : 25,
"id" : 100,
"score" : [ 2, 1, 4, 5, 0, 1, 2, 3, 1]
}
String to JSON Object using GSON
Gson g = new Gson();
Player p = g.fromJson(jsonString, Player.class)
You can also convert Java object to JSON by using method toJson()
String str = g.toJson(p);
JSON String to Java object using JSON-Simple
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(stringToParse);
String to JSON - Jackson Example
Player john = new ObjectMapper().readValue(jsonString, Player.class);

Related

Nested JSONArray

I need to read a JSON file with following form:
{
"Data":[{
"foo":"22",
"bar":"33",
"array":[
{
"1foo":"22",
"1bar":"33"
},
{
"2foo":"22",
"2bar":"33",
}
],
"anotherData":{
"foofoo":"22",
"barbar":"33"
},
"some more data":"11",
"some more data":"11"
},
{and the cycle here starts again from -->
"foo":"22",
"bar":"33",
"array":[
My question stands : How do I access individual elements given it's sometimes JSONObject and sometimes JSONArray. I tried using org.json library but I'm failing to access anything after this line -> "array":[. I tried various combinations of JSONObject and JSONArray up to no avail.
My latest code looked something like this:
List<Data> data= new ArrayList<>();
String rawJson = getJsonAsString();
JSONObject outer = new JSONObject(rawJson);
JSONArray jArr= outer.getJSONArray("Data");
JSONObject inner= outer.getJSONObject("array");
for(int i =0; i<jArr.length(); i++){
JSONObject jsonEvent = jArr.getJSONObject(i);
String foo = jsonEvent.getString("foo"); <-- this works,
String 1foo = jsonEvent.getString("1foo"); <-- but this doesn't and i cant access it
I tried dozens of different solutions(tried myself and tried to find something here as well, but every case with those nested arrays is different and I can't add those solutions together to get answer for my case)
You can increase your readability if you beautify your raw JSON string:
{
"Data":[
{
"foo":"22",
"bar":"33",
"array":[
{
"1foo":"22",
"1bar":"33"
},
{
"2foo":"22",
"2bar":"33"
}
],
"anotherData":{
"foofoo":"22",
"barbar":"33"
},
"some more data":"11",
"some more data":"11"
},
{ and the cycle here starts again from -->
"foo":"22",
"bar":"33",
"array":[
...
],
...
}
]
}
So, stick to the following code:
JSONArray jArr = outer.getJSONArray("Data");
jArr is now filled with array of your Object.
And to loop through your Object array, you can use a for-loop which you have done it correctly.
for (int i = 0; i < jArr.length(); i++) {
// The below gets your Object
JSONObject jsonEvent = jArr.getJSONObject(i);
}
And now each jsonEvent contains your Object, which you can access the Object by their type.
For example, if you would like to access foo, you can use:
String foo = jsonEvent.getString("foo"); // foo = "22"
String bar = jsonEvent.getString("bar"); // bar = "33"
// Note that your array is another Array, you need to get it as JSONArray first
JSONArray arrayJson = jsonEvent.getJSONArray("array");
And as 1foo is in the first Object for your array, you need to access it like this:
JSONObject firstObjectInArray = arrayJson.getJSONObject(0);
String target = firstObjectInArray.getString("1foo"); // target = "22"
And to access foofoo, as it is an attribute of the JSON Object anotherData, so you should obtain anotherData as JSONObject first, and then you can access foofoo:
JSONObject anotherDataObject = jsonEvent.getJSONObject("anotherData");
String foofoo = anotherDataObject.getString("foofoo"); // foofoo = "22"
So the full code within your for-loop should look like this:
for (int i = 0; i < jArr.length(); i++) {
// The below gets your Object
JSONObject jsonEvent = jArr.getJSONObject(i);
String foo = jsonEvent.getString("foo");
JSONArray arrayJson = jsonEvent.getJSONArray("array");
String target = arrayJson.getJSONObject(0).getString("1foo");
// Add to get foofoo
JSONObject anotherDataObject = jsonEvent.getJSONObject("anotherData");
String foofoo = anotherDataObject.getString("foofoo");
}

how to read JsonElement ? "This is not a JSON Array."

I have JsonElement like this:
{
"76800769": {
"prosjekLat": 45.784661646364,
"prosjekLong": 15.947804310909,
"brojCelija": 11
},
"76800772": {
"prosjekLat": 45.7847808175,
"prosjekLong": 15.9477082775,
"brojCelija": 4
},
"2946694": {
"prosjekLat": 45.78475167,
"prosjekLong": 15.9475975,
"brojCelija": 1
},
"76829440": {
"prosjekLat": 45.784726386,
"prosjekLong": 15.947961766,
"brojCelija": 5
}
}
I also create Model:
public class AddMarker {
int cellId;
double longitude;
double latitude;
}
I want to read JSON file and put values to List<AddMarker>.
I'm trying with this:
JsonElement data = response.body();
JsonObject obj = data.getAsJsonObject();
JsonArray arr = obj.getAsJsonArray();
but I'm getting an err: "This is not a JSON Array."
Your JSON is not an array.
Json Array syntax dictates that in order to have an array, your object must be formatted as:
[
{
...
},
{
...
},
...
{
...
}
]
Right now you have the outer square brackets ([]) as curly braces ({}). Change it to square brackets and your code should run correctly.
You're trying to make a array from a single object: JsonArray arr = obj.getAsJsonArray(), where obj is for exemple just this :
"76829440": {
"prosjekLat": 45.784726386,
"prosjekLong": 15.947961766,
"brojCelija": 5
}
you need to get the body from the response and make an array with all these objects, not from a single one
You can use this:
JsonObject json = new JsonObject(data);
String str1 = json.getString("76800769");
JsonObject json2 = new JsonObject(str1);
float str11 = json2.getFloat("prosjekLat");
Using org.json liberary, you can read the element as follows:
JSONObject obj = new JSONObject("your json element");
JSONObject obj2 = (JSONObject) obj.get("76800769");
System.out.println(obj2.get("brojCelija"));
System.out.println(obj2.get("prosjekLat"));
System.out.println(obj2.get("prosjekLong"));
which gives below output:
11
45.784661646364
15.947804310909
I need to convert JSON Object to array. In php just use array_values( $json ).
I solve my problem using this:
json_encode(array_values($izracunatProsjek), true);

converting string into json array with GSON

I am trying to convert string into json array and the iterate over it.
String name = "lokesh";
String response = "[{"name":"lokesh"}, {"name":"cherukuri"}]";
JsonArray jsonArray = gson.fromJson(response, JsonArray.class);
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
System.out.println(jsonObject.get("name"));
if (jsonObject.get("name").toString().equals(name)) {
System.out.println("equal");
}
}
Problem: The If condition inside loop is not true because of quotes. because this line
System.out.println(jsonObject.get("name")); // printed "lokesh"
and System.out.println(name); //printed lokesh
Am i using GSON in a wrong way?
To get the value of the "name" attribute, you need to:
jsonObject.getString("name")
So, your code should be:
System.out.println(jsonObject.getString("name"));
if (jsonObject.getString("name").equals(name)) {
System.out.println("equal");
}
That's because jsonObject.get("name") return a JsonElement object.
If you're sure it's an string, you can get the content by
jsonObject.get("name").getAsString()

Parsing jsot with eclipse: 2d array

My problem is parsing 2d arrays and to fix the erros. Belowe is my jason file, java code and a list of errors.
This 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"
}
},
And this is my java code, i think that the problem is with defining a second array:
try {
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
Iterator i = jsonArray.iterator();
while (i.hasNext()){
JSONObject object = (JSONObject) i.next();
.
.
.
JSONArray productArray = (JSONArray) jsonParser.parse("product");
Iterator j = productArray.iterator();
while (j.hasNext())
{
JSONObject product = (JSONObject) j.next();
long productId = (Long) product.get("productId");
System.out.println("The id is: " + productId);
}`
List of errors:Unexpected character (p) at position 0.
at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at com.domain.project.SveUMain.main(SveUMain.java:66)
It appears the error is coming from this line:
JSONArray productArray = (JSONArray) jsonParser.parse("product");
...
Unexpected character (p) at position 0.
That line of code is going to try to parse the string "product" as if it were a JSON string. It's not, of course, so the parser bails out complaining about the very first character.
If you're trying to access the "product" field of each JSON object, you could do it like this:
Iterator i = jsonArray.iterator();
while (i.hasNext()){
JSONObject object = (JSONObject) i.next();
JSONObject productObj = (JSONObject) object.get("product");
JSON.simple doesn't appear to have a function that would return the product objects from each object in the array with one call.
This json file has a Syntax error.
When you try to validate the file inside an online editor, then it should give you an syntax error on line 1.
A json file starts with an object "{" then inside this you can use your array.
Also the last "," is wrong, because there is no element afterwards. (And you need to close the array "]" and the object "}".
Here are two examples which could be your correct 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"
}
}
And thats the second solution:
{
"array": [
{
"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"
}
}
]
}

Parse JSON object to string in java

I am a newbie to json parsing, I have grabbed a json string from a request and now I need to parse it with java. I'm using simple-lib for this. But I'm really stuck as I'm not familiar with it. I need to extract following data
I used following java code for that but it's not giving me the result I need, please someone help me...
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("test.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("content");
Iterator<String> iterator = msg.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
Sample JSON
{
"status": 200,
"message": "ok",
"timestamp": "2014-05-22T14:29:56.824+03:00",
"pagesCount": 1,
"version": "1.1",
"pages": [
{
"number": 100,
"subpages": [
{
"number": 1,
"timestamp": "2014-05-22T13:41:41.116+03:00",
"content": "text"
},
Something like this perhaps?
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader("test.json"));
JSONArray pages = (JSONArray) jsonObject.get("pages");
if (pages != null) {
for (Object p : pages) {
JSONObject page = (JSONObject) p;
JSONArray subPages = (JSONArray) page.get("subpages");
if (subPages != null) {
for (Object sp : subPages) {
JSONObject subPage = (JSONObject) sp;
System.err.println(subPage.get("content"));
}
}
}
}
You are requesting for the value that corresponds to the key content from your outermost object, but no such key exists in your sample input. In addition, the only field named content has a string as its value and not a JSON array.
To get at the content field you would need to walk the object hierarchy until you reach the element that you need, using something along these lines:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(new FileReader("test.json"));
JSONArray pages = (JSONArray) json.get("pages");
// Page 10
JSONObject page = (JSONObject) pages.get(10);
// Subpages of page 10
JSONArray subpages = (JSONArray) page.get("subpages");
// Subpage 7 of page 10
JSONObject subpage = (JSONObject) subpages.get(10);
// Content of subpage 7 of page 10
String content = (String) subpage.get("content");
Please note that I am assuming that e.g. index 10 corresponds to page 10. That may not be true in your case; pages may not be zero-indexed, there may be missing pages or they may not be in the correct order. In that case you will have to iterate over the page and subpage lists and test the value of the number field to find the object that you need.
In any case, if you are indeed using json-simple, as seems to be the case, then JSONObject is a subclass of HashMap and JSONArray a subclass of ArrayList. Therefore, their interfaces should be quite familiar to you.
Disclaimer: Untested code - exception and other error handling removed for brevity
First of all, The json is not valid (if you pasted it complete)
In JSON "{}" is an object, and "[]" is an array, others are just key value pairs.
Simply you can do like this without using parser ,
JSONObject objResponseJSON = new JSONObject(responseJSONString);
int status = (int) objResponseJSON.getInt("status");
//fetch other
JSONArray pages = objResponseJSON.getJSONArray("pages");
for(int count = 0; count < pages.length(); count++){
//fetch other
JSONObject objJSON = pages.getJSONObject(count);
JSONArray subpages = objJSON.getJSONArray("subpages");
for(int count1 = 0; count1 < subpages.length(); count1++){
JSONObject objSubpageJSON = subpages.getJSONObject(count1);
//fetch other
int number = (int) objSubpageJSON.getInt("number");
}
}

Categories