Reputation: 31
i've been searching a lot for a way to convert a normal String, not an Array, and i'm stuck in my code. I've programmed an API that return me the following json
[{
"Id": "6d052279342d66d1ae4d4a84da0f98b80313277a3faeca4d7e822076c9dd4316",
"Names": ["/elegant_bartik"],
"Image": "alpine",
"ImageID": "sha256:3fd9065eaf02feaf94d68376da52541925650b81698c53c6824d92ff63f98353",
"Command": "/bin/sh",
"Created": 1525954440,
"Ports": [],
"Labels": {},
"State": "running",
"Status": "Up About an hour",
"HostConfig": {
"NetworkMode": "default"
},
"NetworkSettings": {
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "430ff6d43b361b0a2f45046c575862ca4785216a0242e72d145c269f3ef326df",
"EndpointID": "a7a2012d7841af6b5b76e24f57b13a5057252b511e8dbfb48e74aa1cc19e30b4",
"Gateway": "172.17.0.1",
"IPAddress": "172.17.0.2",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "02:42:ac:11:00:02",
"DriverOpts": null
}
}
},
"Mounts": []
}]
The problem is, I need to put it into an JSONObject, is there any function or sequence of functions that could do that? Or do I need to break the whole String?
I've tried JSONParse, Gson(from Google) and a lot more, but none of then works.
Thanks!
Upvotes: 0
Views: 494
Reputation: 191
First, the json array string looks okay. you will have to read it as a jsonArray, then loop through each getting the jsonObjects.
JSONArray jsonArray = new JSONArray(readlocationFeed);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
}
I hope this helps.
Upvotes: 1
Reputation: 2759
The JSON you have posted is an array (denoted by []
) containing a single object (denoted by {}
)
You will first need to parse the JSON into an array, for example (using GSON):
JsonArray arr = new Gson().fromJson(string, JsonArray.class)
And then you can access the first object in the array:
JsonElement ele = arr.get(0);
Upvotes: 2
Reputation: 4444
That's a JSONArray. You first need to get the root json array. Then you can get the first object from that.
Upvotes: 0