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

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

Related

Adding json array in a json object in java

I am struggling to fit in a jsonArray inside a json object (through java code).. please help me out.
My Input JsonObject is :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W"
}
}
I will have to read "imageURL" property from this JSONObject and append its variants to the same json object (image variants will be in SortedSet data structure).
Sample O/P 1 :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W",
"variants":[
"http:example.com/imageResource_variant1.jpg",
"http:example.com/imageResource_variant2.jpg"
]
}
}
Sample O/P 2 :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W",
"variants":[
{
"url" : "http:example.com/imageResource_variant1.jpg"
},
{
"url" : "http:example.com/imageResource_variant2.jpg"
}
]
}
}
The logic i tried to get sample output 2 is some what like below,
// productDetail is the give input JSONObject
JSONObject product = productDetail.optJSONObject("products");
SortedSet<String> imageUrls = new TreeSet<>();
imageUrls.add("http:example.com/imageResource_variant1.jpg");
imageUrls.add("http:example.com/imageResource_variant2.jpg");
Iterator<String> itr = imageUrls.iterator();
JSONArray imageUrlsArray = new JSONArray();
while (itr.hasNext()) {
JSONObject imageUrlObj = new JSONObject();
imageUrlObj.put("url", itr.next());
imageUrlsArray.put(imageUrlObj);
}
product.append("variants", imageUrlsArray);
When i tried to print the productDetail JSON object after executing above logic
System.out.println(productDetail.toString());
I observed the following output :
{
"products":{
"productId":"712161780324",
"imageURL":"http:example.com/imageResource.jpg",
"internalItemCode":"N08792 8W",
"variants":[
[
{
"url" : "http:example.com/imageResource_variant1.jpg"
},
{
"url" : "http:example.com/imageResource_variant2.jpg"
}
]
]
}
}
If you notice, It's coming up like Array of arrays (extra [ ] for "variants"),
Please help me in understanding Where my logic is going wrong.
And also, Please help me getting the First sample out put.
Appreciate quick response..
Thanks,
Rohit.
First sample can be archivable as simple as this:
JSONObject product = productDetail.optJSONObject("products");
JSONArray imageUrlsArray = new JSONArray();
imageUrlsArray.put(0, "http:example.com/imageResource_variant1.jpg");
imageUrlsArray.put(1, "http:example.com/imageResource_variant2.jpg");
product.append("variants", imageUrlsArray);
Try using put instead of append:
JSONObject product = productDetail.optJSONObject("products");
SortedSet<String> imageUrls = new TreeSet<>();
imageUrls.add("http:example.com/imageResource_variant1.jpg");
imageUrls.add("http:example.com/imageResource_variant2.jpg");
Iterator<String> itr = imageUrls.iterator();
JSONArray imageUrlsArray = new JSONArray();
while (itr.hasNext()) {
JSONObject imageUrlObj = new JSONObject();
imageUrlObj.put("url", itr.next());
imageUrlsArray.put(imageUrlObj);
}
-product.append("variants", imageUrlsArray);
+product.put("variants", imageUrlsArray);
From the docs:
Append values to the array under a key. If the key does not exist in the JSONObject, then the key is put in the JSONObject with its value being a JSONArray containing the value parameter. If the key was already associated with a JSONArray, then the value parameter is appended to it.

Convert string to json doesn't work 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);

add array to json file with no key

I have to make a file in JSON format which must look like the following:
xyz.json
[
{
"imagelist": "/oracle/public/oel6",
"label": "test_higgs",
"shape": "small",
"name" : "/Compute-computecli1/computeadmin/",
"networking" : {
"eth0" : {
"ipnetwork" : "/Compute-computecli1/computeadmin/ipnet"
}
}
}
]
The array should be added in the JSON file without {}, and these curly brackets have to come inside the JSON array.
The code for
{
instances:[
{
"imagelist": "/oracle/public/oel6",
"label": "test_higgs",
"shape": "small",
"name" : "/Compute-computecli1/computeadmin/",
"networking" : {
"eth0" : {
"ipnetwork" : "/Compute-computecli1/computeadmin/ipnet"
}
}
}
]
}
is:
This code adds json array as a value to "instance" key, but I want to add json array without json key.
JsonObject ipnetwork = new JsonObject();
ipnetwork.addProperty("ipnetwork", ipNetworkName);
JsonObject interface_type = new JsonObject();
interface_type.add("eth0", ipnetwork);
JsonObject instance = new JsonObject();
instance.addProperty(imageListCmdText, "/oracle/public/oel6");
instance.addProperty("label","test_higgs");
instance.addProperty("shape","small");
instance.addProperty("name","/"+customerName);
instance.add("networking",interface_type);
JsonArray instances = new JsonArray();
instances.add(instance);
JsonObject launch_plan = new JsonObject();
launch_plan.add("instances", instances);
Please tell how does this code has to be changed in order to get the output asked above.
JsonObject launch_plan = new JsonObject();
launch_plan.add("instances", instances);
These two lines create the JSON object with curly braces. You don't need them, you can just remove them and use instances, which doesn't have curly braces as it's a json array and not a json object.
JsonObject ipnetwork = new JsonObject();
ipnetwork.addProperty("ipnetwork", ipNetworkName);
JsonObject interface_type = new JsonObject();
interface_type.add("eth0", ipnetwork);
JsonObject instance = new JsonObject();
instance.addProperty(imageListCmdText, "/oracle/public/oel6");
instance.addProperty("label","test_higgs");
instance.addProperty("shape","small");
instance.addProperty("name","/"+customerName);
instance.add("networking",interface_type);
JsonArray instances = new JsonArray();
instances.add(instance);
// not needed
//JsonObject launch_plan = new JsonObject();
//launch_plan.add("instances", instances);

Extract json subset with few attributes from the main json

Is there an API/tool available for extracting specific attributes(json subset) of a json in java, similar to apache-commons beanutils copy?
For example I have the following JSON
{
"fixed":[
{
"b":"some value",
"c":"some value",
"d":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"c":"value",
"d":"value",
"e":"value",
"f":"value"
}
]
}
I would like to have the following json
{
"fixed":[
{
"b":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"e":"value",
"f":"value"
}
]
}
I came up the following method, but not sure if its the right approach
public JSONObject parseJSON(JSONObject data,List<String> subset){
JSONArray fixedArray = (JSONArray) data.get("fixed");
JSONObject resObj = new JSONObject();
JSONArray resArray = new JSONArray();
for(int i=0;i<fixedArray.size();i++){
JSONObject element = (JSONObject) fixedArray.get(i);
JSONObject resElement = new JSONObject();
for(String s:subset){
resElement.put(s, element.get(s));
}
resArray.add(resElement);
}
return resObj.put("fixed", resArray);
}
I had a look at this SO question, but wasn't helpful for this topic.
https://docs.oracle.com/javase/tutorial/jaxb/intro/arch.html you can also create you own pojo class from JAXB ,if you want.

Convert JSON String to JSON Array

Hello i call a service if it contains multiple objects it make list but when it contain only one object it return a single object not a list [] are missing , actually i want to convert them into java class using gson but in case of single exception it throw exception but when it contain list it work fine i actually need to convert my single gSON string to array ,please help me ..here is the string
{
"response":{
"projects":{
"project":{
"ixWorkflow":1,
"sEmail":"j.a#loxvo.com",
"sPhone":"",
"ixProject":2,
"ixPersonOwner":2,
"fDeleted":false,
"sProject":"Project Default",
"fInbox":true,
"sPersonOwner":"junaid"
}
}
}
}
i want it to be like same as
{
"response":{
"projects":{
"project":[
{
"ixWorkflow":1,
"sEmail":"j.a#loxvo.com",
"sPhone":"",
"ixProject":6,
"ixPersonOwner":2,
"fDeleted":false,
"sProject":"project 2",
"fInbox":false,
"sPersonOwner":"junaid"
},
{
"ixWorkflow":1,
"sEmail":"j.a#loxvo.com",
"sPhone":"",
"ixProject":2,
"ixPersonOwner":2,
"fDeleted":false,
"sProject":"Project Default",
"fInbox":true,
"sPersonOwner":"junaid"
}
]
}
}
}
With reference to https://stackoverflow.com/a/7284813/1105291
Please try below code before you pass json to Gson for object conversion, and please let me know if you get any error. Only posibility that I can see is exception at if.
JSONObject jsonObject = new JSONObject(responseString);
JSONObject projectsJsonObject = jsonObject.getJSONObject("response").getJSONObject("projects");
if(projectsJsonObject.getJSONArray("project") == null)
{
JSONArray jsonArray = new JSONArray();
jsonArray.put(projectsJsonObject.getJSONObject("project"));
projectsJsonObject.put("project", jsonArray);
}
//Pass jsonObject to Gson
Use Google Gson
JsonParser parser = new JsonParser();
JsonObject o = (JsonObject)parser.parse("{\"a\": \"A\"}");

Categories