1

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."

Goran Belačić
  • 81
  • 2
  • 10
  • 6
    `{...}` is object, `[...]` is array, – Pshemo Jun 01 '17 at 17:18
  • Possible duplicate of [Parsing Json Array resulting in This is not a JSON Array exception](https://stackoverflow.com/questions/19780576/parsing-json-array-resulting-in-this-is-not-a-json-array-exception) – crizzis Jun 01 '17 at 19:56

5 Answers5

2

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.

Jeeter
  • 5,887
  • 6
  • 44
  • 67
0

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

Yasmin B.
  • 21
  • 2
0

You can use this:

JsonObject json = new JsonObject(data);
String str1 = json.getString("76800769");
JsonObject json2 = new JsonObject(str1);
float str11 = json2.getFloat("prosjekLat");
Jeeter
  • 5,887
  • 6
  • 44
  • 67
Sai Kishore
  • 326
  • 1
  • 7
  • 16
  • You should probably explain *why* OP should use your solution, rather than supplying just code – Jeeter Jun 01 '17 at 18:13
0

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

0

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);
Goran Belačić
  • 81
  • 2
  • 10