Converting a normal String to JSON in java - java

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!

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

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.

That's a JSONArray. You first need to get the root json array. Then you can get the first object from that.

Related

Want to read JSONArray with JSONObject, but got the error A non-empty JSON Pointer

My Json FILE (it´s an array! )
[
{
"datasetid": "country-flags",
"recordid": "d661d0a8676bf4d7563114c1d9c465987df22132",
"fields": {
"num_un": 32,
"geolocation": [
-38.416097,
-63.616672
],
"dialing_code": "54",
"a3_un": "ARG",
"country": "Argentina",
"flag": {
"mimetype": "image/png",
"format": "PNG",
"filename": "ar.png",
"width": 16,
"id": "fceb4235ce95c8597bfa77d0db0181a0",
"height": 11,
"thumbnail": true
},
"a2_iso": "AR"
},
"geometry": {
"type": "Point",
"coordinates": [
-63.616672,
-38.416097
]
},
"record_timestamp": "2016-09-26T07:48:38.162+02:00"
},
more...
]
So i want to get the value from coordinates. So for this i tried to work with this:
JsonReader jsonReader = Json
.createReader(new FileReader(getClass().getResource("country-flags.json").getPath()));
JsonArray arr = jsonReader.readArray();
for(int i = 1; i<arr.size();i++)
{
JsonObject obj = arr.getJsonObject(i);
System.out.println("coordinates: " + obj.containsKey("\"coordinates\""));
System.out.println("##########");
System.out.println(obj.getValue("\"coordinates\""));
}
But i got the error:
javax.json.JsonException: A non-empty JSON Pointer must begin with a
'/'
Can someone help me out ?!
Your code obj.containsKey("\"coordinates\"") will return false as coordinates is NOT a top level key, but is a 2nd level (nested) key. If you print obj.keySet(), you will get [datasetid, recordid, fields, geometry, record_timestamp] (first / top level keys only).
If the structure of your JSON is fixed, you can use the following code:
for(int i = 1; i<arr.size();i++)
{
JsonObject obj = arr.getJsonObject(i);
JsonObject jsonChildObject = obj.getJsonObject("geometry");
if(jsonChildObject.containsKey("coordinates"))
System.out.println(jsonChildObject.getValue("/coordinates"));
}
Notice the / in front of the getValue method's coordinates param. I think that was the reason you were here in the first place.

how to get array of objects from server

I'm trying to have a list of objects from a server. But I don't know how to do it exactly and at least print it in System.out.print
server sends data like that:
[
{
"userId": "15",
"routeId": "10",
"driverId": "2",
"text": "ytf",
"timestamp": "2018-05-25 13:04:01"
},
{
"userId": "15",
"routeId": "33",
"driverId": "2",
"text": "asd",
"timestamp": "2018-05-25 13:07:40"
}
]
And model:
https://pastebin.com/52mc5Gmw
https://pastebin.com/DnUTtkPC
Controller: https://pastebin.com/ucJFFJyy
And the API:
#GET("getReviews.php")
Call<List<reviewResult>> getReview();
You can use JSONArray for parse the array, and JSONObject for get each object of the array
Edit Add a example
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length();i++)
{
JSONObject object = jsonArray.getJSONObject(i);
System.out.print(object);
}
From your code, looks like the expected return type should be List of reviewResponse objects. You should change the API to:
Call<List<reviewResponse>> getReview();
From there it's obvious how to retrieve the data you ask

Android: org.json.JSON.typeMismatch

I've got a method below, which is parsing JSON. However I've run into an error (which you can see from the title), where it is saying "org.json.JSON.typeMismatch" .
Trying to log the names that are getting output however having no luck. I've little experience with cracking JSON (as you can probably tell from this), so wondering how to go about fixing this issue.
private Boolean parse()
{
try
{
JSONArray ja=new JSONArray(jsonData);
JSONObject jo;
realms.clear();
for (int i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
String name = jo.getString("name");
Log.d("",name);
//realms.add(name);
}
return true;
} catch (JSONException e) {
e.printStackTrace();
return false;
}
}
And the JSON I am trying to parse into here is:
{
"realms": [{
"type": "pvp",
"population": "low",
"queue": false,
"status": true,
"name": "Aegwynn",
"slug": "aegwynn",
"battlegroup": "Misery",
"locale": "de_DE",
"timezone": "Europe/Paris",
"connected_realms": ["aegwynn"]
}, {
"type": "pve",
"population": "low",
"queue": false,
"status": true,
"name": "Aerie Peak",
"slug": "aerie-peak",
"battlegroup": "Reckoning / Abrechnung",
"locale": "en_GB",
"timezone": "Europe/Paris",
"connected_realms": ["bronzebeard", "aerie-peak"]
}]
(there is more to this but I'd rather not copy it all)
Not sure if perhaps I'm not addressing the "realms" array? Just would appreciate any help on this! As I can't see quite why I'm getting a mismatch?
Kind Regards
J G
Your JSON string show up here it is a JSONObject not a JSONArray, so that you must init an JSONObject with this string, after that get a JSONArray with name realms from previous JSONObject. Here is an example for your reference

how to parse this response using JSONObject

I have this response that I get back form server. I want to parse it and get the hospital_name out of it. How would I go about it?
[
{
"Hospital": {
"id": "63083",
"hospital_name": "Colorado Mental Health Inst",
"hospital_add_1": "1600 W 24th St",
"hospital_add_2": null,
"hospital_city": "Pueblo",
"hospital_state": "CO",
"hospital_zip": "81003",
"hospital_phone": "719-546-4000\r",
"hospital_fax": null,
"hospital_description": null,
"callcenter_agent_approval": "0",
"hospital_site": "",
"mdpocket_approval": "0",
"facebook": ""
},
"Floor": [],
"Department": [],
"Image": [],
"Notes": []
},
{
"Hospital": {
"id": "63084",
"hospital_name": "Parkview Medical Center",
"hospital_add_1": "400 W 16th St",
"hospital_add_2": null,
"hospital_city": "Pueblo",
"hospital_state": "CO",
"hospital_zip": "81003",
"hospital_phone": "719-584-4000\r",
"hospital_fax": null,
"hospital_description": null,
"callcenter_agent_approval": "0",
"hospital_site": "",
"mdpocket_approval": "0",
"facebook": ""
},
"Floor": [],
"Department": [],
"Image": [],
"Notes": []
},
{
"Hospital": {
"id": "63085",
"hospital_name": "St Mary-Corwin Medical Center",
"hospital_add_1": "1008 Minnequa Ave",
"hospital_add_2": null,
"hospital_city": "Pueblo",
"hospital_state": "CO",
"hospital_zip": "81004",
"hospital_phone": "719-560-4000\r",
"hospital_fax": null,
"hospital_description": null,
"callcenter_agent_approval": "0",
"hospital_site": "",
"mdpocket_approval": "0",
"facebook": ""
},
"Floor": [],
"Department": [],
"Image": [],
"Notes": []
}
]
EDITED THE JSON
*UPDATED JSON *
[ // json array node
{ // json object node
"Hospital": { // json object Hospital
To parse
JSONArray jr = new JSONArray("jsonstring");
for(int i=0;i<jr.length();i++)
{
JSONObject jb = (JSONObject)jr.getJSONObject(i);
JSONObject jb1 =(JSONObject) jb.getJSONObject("Hospital");
String name = jb1.getString("hospital_name");
Log.i("name....",name);
}
Log
02-18 03:09:43.950: I/name....(951): Colorado Mental Health Inst
02-18 03:09:43.950: I/name....(951): Parkview Medical Center
02-18 03:09:43.950: I/name....(951): St Mary-Corwin Medical Center
You won't- its invalid JSON. You're missing most of your "" around field names.
Try this..
JSONArray tot_array = new JSONArray(response);
for(int i = 0; i< tot_array.length(); i++){
JSONObject obj = tot_array.getJSONObject(i);
JSONObject hospital_obj = obj.getJSONObject("Hospital");
String hospital_name = hospital_obj.getString("hospital_name");
}
I recommend you use the fastjson (https://github.com/alibaba/fastjson).
Checkout this cool libray for parsing JSOn in Android its called GSON https://code.google.com/p/google-gson/ . Via this parsing this very simple.
Your string is not a valid JSON object. Check out jsonlint before trying to parse a string as JSON. After which, you can read about parsing JSON in Android. It's easy enough with the built-in org.json, but should be much easier if you use one of the many Java libraries out there that simplifies it further. You can look into Jackson or google-gson, two of the most capable utilities for your purpose.

how to retrieve JSON object from the JSON array

I am having the below JSON. Inside this JSON I am having "ticketDetails" as JSON array. From this array I want to retrieve the value of ticketPrice inside the json object "amount". How can I do that?
{
"ticketDetails": [{
"seq": 1,
"qty": 2,
"amount": {
"ticketPrice": 120,
"bookingFee": 50
},
"session": {
"id": 1001,
"date": "2013, 9, 15",
"time": "1300"
},
"venue": {
"id": "MTRG",
"name": "Adlabs Manipur",
"companyCode": "ADLB"
},
"event": {
"id": "ET00000001123",
"name": "Chennai Express",
"producerCode": "YRF"
},
"category": {
"ttypeCode": "00012",
"areaCatCode": "2414",
"type": "Gold",
"price": 270
}
}]
}
Any suggestion will helpful...
Below is the sample code for retrieving the ticketPrice from the given JSONObject:
JSONObject objData = (JSONObject)JSONSerializer.toJSON(data);
JSONArray objTicketDetailsJsonArr = objData.getJSONArray("ticketDetails");
for(int nSize=0; nSize < objTicketDetailsJsonArr.size(); nSize++){
String ticketPrice = "";
ticketPrice = objTicketDetailsJsonArr.getString("ticketPrice");
}
Below are the imports for the above code:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
source of JAR: http://json-lib.sourceforge.net/
you store your data within a variable
data = {...}
then you access it this way:
data.ticketDetails[0].amount.ticketPrice
if the ticketDetails have more than one element
you can loop over the ticketDetails array and store all the ticketPrice values within an other array, ticketPriceArray
the following would work fine in JavaScript:
var ticketPriceArray = data.ticketDetails.map(function(k){
return k.amount.ticketPrice;
});
if you are using another programming language a general loop would work fine also
for ( i; i< ticketDetails.length ; i++){
ticketPriceArray[i] = data.ticketDetails.amount.ticketPrice[i];
}
For Java check this tutorial:
http://answers.oreilly.com/topic/257-how-to-parse-json-in-java/
you can try this code:
JsonObject transactiondata = (JsonObject)Offer.get("transData");
JsonObject ticketdata = (JsonObject)transactiondata.get("tickets");
JsonObject offerData = (JsonObject)Offer.get("offerData");
JsonObject offerData1 = (JsonObject)offerData.get("offerconfig");
JsonArray jsonarr= (JsonArray)ticketdata.get("ticketDetails");
double ticketPrice = Double.parseDouble(jsonarr.get(0).getAsJsonObject().get("amount").getAsJsonObject().get("ticketPrice").getAsString());
System.out.println("ticketPrice:"+ticketPrice);

Categories