Can't get Json android - java

I want output json, but I have error
06-02 23:10:26.110: W/System.err(23235): org.json.JSONException: Value data of type java.lang.String cannot be converted to JSONObject
06-02 23:10:26.116: W/System.err(23235): at org.json.JSON.typeMismatch(JSON.java:111)
06-02 23:10:26.117: W/System.err(23235): at org.json.JSONObject.<init>(JSONObject.java:158)
06-02 23:10:26.117: W/System.err(23235): at org.json.JSONObject.<init>(JSONObject.java:171)
I create my code whith example, its my json:
{
"status": "success",
"data": {
"users_information": [
{
"id": "1",
"active": "1",
},
{
"id": "2",
"active": "1",
}]}}
It's my code:
JSONObject data = new JSONObject("data");
JSONArray userInform = data.getJSONArray("users_information");
for(int i = 0; i < userInform.length(); i++) {
JSONObject c = userInform.getJSONObject(i);
Log.e("id ", c.getString("id"));
}

String data = "{
"status": "success",
"data": {
"users_information": [
{
"id": "1",
"active": "1",
},
{
"id": "2",
"active": "1",
}]}}"
parse Json
JSONObject data = new JSONObject(data);
JSONArray userInform = data.getJSONArray("users_information");
for(int i = 0; i < userInform.length(); i++) {
JSONObject c = userInform.getJSONObject(i);
Log.e("id ", c.getString("id"));
}
The string data json can be replaced by the JSON received from backend

I dont recommend json deserialization like this. Try using at least Gson library. With it you will can create class with same structure like your json and it will parse in single line.

JSONObject data = new JSONObject("data");
You have to place the JSON String where "data" is placed. "data" is just a string and no json like you posted in your example.
If for any reason "data" is your string reference to your JSON String, then you accidentally added the quotes (") which let android interpret it as a String not a reference to a String.

Related

Java: Array of Arrays from JSON

I have a JSON Arrays of Array like this
"results": [
{
"id": "AAA",
"color": "#4D4837",
"links": {
"self": "https://aaa.com",
"html": "https://bbb.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3891,
},
{
"id": "BBB",
"color": "#4D453",
"links": {
"self": "https://abb.com",
"html": "https://bcc.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3000,
}
]
And I would like to retrieve "https://bbb.com" and "https://bcc.com" of "html", but I don't know how to do that.
Based on kindly comment, I put the following.
somehow, "getJSONObject()"can not be put. The error message says "Cannot resolve method 'getJSONObject' in 'JSONArray'".
JSONArray array = new JSONArray((Collection) jobjt.get("Strings"));
for (int i =0 ; i<2 ; i++){
JSONObject job = (JSONObject) array.get(i); --> get(i) can not be changed to getJSONObject(i)
String id = job.get("id").toString();
String color = job.get("color").toString();
String photoUrl = job.get("links").toString(); --> By updating here, I want to store only "https://bbb.com" and "https://bcc.com".
}
But when I tried to use the following, not only "html", but "self" and the other information are retrieved.
String photoUrl = job.get("links").toString();
Please tell me how to retrieve only "html".
I am using IntelliJ.
Steps to be followed(assuming you have proper JSONArray you mentioned):
get JSONObject from your JSONArray by index ie. for your case, index=0 here
Get the inner JSONObject by key of links
Now, access your content by key of html
Example for your case:
JSONObject indexedObject = jsonArray.getJSONObject(0);
JSONObject linksObject = indexedObject.getJSONObject("links");
String html= linksObject.getString("html");
Better keep checking if key exists as Harshal suggests

Convert JSON Objects from JsonSlurper back to an appended JSONArray - Groovy

I have a json arrary with many json messsages. I then parse the json message to process each json object.
I need to figure out how to take a single json object that fails and append all the failed json objects back
into another json array to create a new file. I'm not sure how to convert a json object from the parseText() method
back to a normal json message or how to append objects back into a json array to create a file. Can someone help me with this?
Main json file array
[
{
"Account": "1",
"Name": "Test1"
},
{
"Account": "2",
"Name": "Test2"
},
{
"Account": "3",
"Name": "Test3"
},
{
"Account": "4",
"Name": "Test4"
}
]
String sJson = groovy.json.StringEscapeUtils.unescapeJava(jsonFile.toString());
jsonResp = new groovy.json.JsonSlurper().parseText(sJson));
for( int x=0; x < jsonResp?.size(); x++ ) {
processJson( jsonResp[x] )
}
void processJson( Object jsonResp ) {
If object message fails in this function, need to convert the json object back into a json message
and append it to a jsonArray to create a new json file.
}
This is what the new json file would like if test samples 2 & 4 failed
[
{
"Account": "2",
"Name": "Test2"
},
{
"Account": "4",
"Name": "Test4"
}
]
I found the answer to my question.
JSONArray jsonArray = new JSONArray();
jsonArray.add(jsonResp);
println jsonArray.toString()

How to dynamically simplify json using java?

I have received a json string like so:
{
"data": [
{
"name": "Order",
"value": "2"
},
{
"name": "Address",
"value": "182"
},
{
"name": "DNS",
"value": "null"
},
{
"name": "SSID",
"value": "work"
},
{
"name": "Protocol",
"value": "0"
},
{
"name": "Key",
"value": ""
},
{
"name": "carrier",
"value": "undefined"
},
{
"name": "SSH",
"value": "1"
},
{
"name": "ntp_addr",
"value": ""
},
{
"name": "Name",
"value": ""
}
]
}
I used stringify on an html response and this is what I have to parse. As you can see, it is pretty redundant; I would much rather { "Order":"2" } than { "name":"Order","value":"2" } ... So an array of name-value pairs, instead of an array of objects.
Is there a way I can dynamically format this response so that it will be easier to parse?
What 'd like is to be able to say:
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject dataObject = data.getJSONObject(i);
String order = dataObject.getString("Order");
String address = dataObject.getString("Address");
// etc...
}
But the current format makes it almost impossible to parse. I'd need loops within loops.
I'd like to use com.google.gson library. And this response easy to parse with it:
private final JsonParser PARSER = new JsonParser();
public void parse(String jsonString) {
JsonObject dataObject = PARSER.parse(jsonString).getAsJsonObject();
JsonArray dataArray = dataObject.get("data").getAsJsonArray();
dataArray.iterator().forEachRemaining(element -> {
String name = element.getAsJsonObject().get("name").getAsString();
String value = element.getAsJsonObject().get("value").getAsString();
}
}
Or you can simply use TypeAdapters for json deserialization directly in the object.
Something like this should do the trick
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONArray data = jsonObject.getJSONArray("data");
JSONObject simplifiedDataObject = new JSONObject();
for (int i = 0; i < data.length(); i++) {
JSONObject dataField = data.getJSONObject(i);
simplifiedDataObject.put(dataField.getString("name"), dataField.get("value"));
}
You just iterate over each element in data, use the name field as the field on a new JSONObject and simply retrieve the value using the value key.

should value must be quoted in JSON along with key

i have data
like this:
{
"status": "success",
"message": "Student Statement Report",
"data": {
"data": [{
"id": "45",
"transaction_no": "45",
"transaction_date": "2017-05-25",
"transaction_type": "invoice",
"transaction_amount": "1010.00",
"related_invoice_id": "45",
"balance_amount": "1010.00",
"related_user_id": "436",
"related_user_group": "student",
"description": "",
"created_by": "Principal",
"updated_by": "Principal",
"created_at": "2017-05-25 11:57:39",
"updated_at": "2017-05-25 11:57:39"
}],
"opening_balance": 0,
"dates": ["2017-05-22 00:00:00", "2017-05-28 23:59:59"]
}
}
JSONObject jsonObject = new JSONObject(response);
and i am geeting Json expection error from here
String openingBalance = jsonObject.getString("opening_balance");
"opening_balance": 0,
so, my biggest question is should that zero (value) should be quoted or not?
You have to parse it like this:
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");//Get Data object
int openingBalance = data.getInt("opening_balance");//Get opening balance
If you read the number as an Integer then quotation is not necessary. But if your read it as a String then you have to put quotation.
To read as an Integer you can use getInt("json_key")
& for String getString("json_key").
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");//Get Data object
int openingBalance = data.getInt("opening_balance");//Get opening balance

How to parse JSON with another json inside in java?

This is my JSON:
{
"results": [
{
"username": "bigglesworth",
"phone": "650-253-0000",
"createdAt": "2011-11-07T20:58:06.445Z",
"updatedAt": "2011-11-07T20:58:06.445Z",
"objectId": "3KmCvT7Zsb"
},
{
"username": "cooldude6",
"phone": "415-369-6201",
"createdAt": "2011-11-07T20:58:34.448Z",
"updatedAt": "2011-11-07T21:25:10.623Z",
"objectId": "g7y9tkhB7O"
}
]
}
How can I parse this json?
When I tried to parse this using jason I retrived this error message
"Exception in thread "main"
com.fasterxml.jackson.databind.JsonMappingException: Can not
deserialize instance of java.util.ArrayList out of START_OBJECT
token"
Without third party libraries, you can do something like
JSONObject jsonObject = new JSONObject(jsonAsString);
JSONArray results = jsonObject.getJSONArray("results");
for(int i=0; i<results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String username = result.getString("username");
//...
}

Categories

Resources