Json array is not of proper format - android

Im trying to frame a json array of following form
[
"1-35e03ac0b6ba442bb0d5fab3faef32fe",
{
"request": [
"UpdateComplianceDetail",
{
"remarks": "Remarks",
"next_due_date": "27-Mar-2016",
"completion_date": "04-Apr-2016",
"validity_date": null,
"documents": null,
"compliance_history_id": 23
}
],
"session_token": "1-35e03ac0b6ba442bb0d5fab3faef32fe"
}
]
Following is my code that i use to create json of above structure,
private JSONArray getJsonArray(String encodedString) {
JSONArray docArray = new JSONArray();
JSONObject innerJson = new JSONObject();
JSONArray innerJsonArray = new JSONArray();
JSONObject inJobj = new JSONObject();
JSONArray outerJsonArray = new JSONArray();
SharedPreferences userDetails = getSharedPreferences("userdetails", Context.MODE_PRIVATE);
String session = userDetails.getString("session", "");
try {
innerJson.put("compliance_history_id", 23);
docArray.put("null");
innerJson.put("documents", docArray);
innerJson.put("completion_date", "04-Apr-2016");
innerJson.put("validity_date", mValidityDate.getText().toString());
innerJson.put("next_due_date", mNextDueDate.getText().toString());
innerJson.put("remarks", mRemarks.getText().toString());
innerJsonArray.put("UpdateComplianceDetail");
innerJsonArray.put(innerJson);
inJobj.put("session_token", session);
inJobj.put("request", innerJsonArray);
outerJsonArray.put(session);
outerJsonArray.put(inJobj);
} catch (JSONException e) {
e.printStackTrace();
}
return outerJsonArray;
}
Following is the json that my code is creating,
[
"1-35e03ac0b6ba442bb0d5fab3faef32fe",
{
"request": [
"UpdateComplianceDetail",
{
"remarks": "Remarks",
"next_due_date": "27-Mar-2016",
"completion_date": "04-Apr-2016",
"validity_date": "null",
"documents": [
"null"
],
"compliance_history_id": 23
}
],
"session_token": "1-35e03ac0b6ba442bb0d5fab3faef32fe"
}
]
How can I be able to sort this out? I have put "null" within json array but its being recognised as a string and not as a null. also validity_date has to be null but it is a string "null"

docArray.length > 0 ? docArray : null evaluates the length of docArray. If it's length is greater than 0 (aka, it contains items), it will put the array as the content of documents. Otherwise it will put null.
Same thing for validity_date. isEmpty() checks for null or "" and if that's the case, null will be used in stead of the actual value of mValidityDate.getText().
private JSONArray getJsonArray(String encodedString) {
JSONArray docArray = new JSONArray();
JSONObject innerJson = new JSONObject();
JSONArray innerJsonArray = new JSONArray();
JSONObject inJobj = new JSONObject();
JSONArray outerJsonArray = new JSONArray();
SharedPreferences userDetails = getSharedPreferences("userdetails", Context.MODE_PRIVATE);
String session = userDetails.getString("session", "");
try {
innerJson.put("compliance_history_id", 23);
innerJson.put("documents", docArray.length > 0 ? docArray : JSONObject.NULL);
innerJson.put("completion_date", "04-Apr-2016");
String validityDate = mValidityDate.getText().toString();
innerJson.put("validity_date", validityDate.isEmpty() ? JSONObject.NULL : validityDate.toString());
innerJson.put("next_due_date", mNextDueDate.getText().toString());
innerJson.put("remarks", mRemarks.getText().toString());
innerJsonArray.put("UpdateComplianceDetail");
innerJsonArray.put(innerJson);
inJobj.put("session_token", session);
inJobj.put("request", innerJsonArray);
outerJsonArray.put(session);
outerJsonArray.put(inJobj);
} catch (JSONException e) {
e.printStackTrace();
}
return outerJsonArray;
}

Try using JSONObject.NULL
reference:
http://developer.android.com/reference/org/json/JSONObject.html#NULL
How do you set a value to null with org.json.JSONObject in java?

Related

Get a nested value from a json api

I have this json code
{
"status": "success",
"message": null,
"data": {
"19": {
"id": "19",
"created": "2019-01-07 13:26:06",
"createdby": 158,
"touched": "2019-01-07 13:26:06",
"touchedby": 158,
"start": "2019-01-07",
"end": "2019-01-08",
"scoperole": 3,
"scopecorp": 1,
"body": "<p>test</p>",
"language": "en"
},
"20": {
"id": "20",
"created": "2019-01-07 13:26:20",
"createdby": 158,
"touched": "2019-01-07 13:26:20",
"touchedby": 158,
"start": "2019-01-07",
"end": "2019-01-08",
"scoperole": 3,
"scopecorp": 1,
"body": "<p>test1</p>",
"language": "en"
}
},
"error": 0,
"line": 1515,
"debug": null
}
And i want to take the values of "body" (test,test1).
How can i reach them?I left the code that i tried just to see it with //not working next to it.Any ideas please?Also the 19,20 are not the same so i'm not able to get them by just putting the name of a variable(ex JSONObject dataObj =new JSONObject ("data");
Here is my code
private void getJson() {
URL obj = null;
try {
obj = new URL("https://gekon.technologypark.cz/api/v1/notification/");
HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("ApiSecret", LoginInfo.ApiSecret);
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
while ((output = br.readLine()) != null)
sb.append(output);
JSONObject jsonObj = new JSONObject(sb.toString());
Log.d("test", "response" + jsonObj);
JSONObject dataObj =new JSONObject("data");
JSONObject dataObj19 =dataObj.getJSONObject("22");
String body1 =dataObj19.getString("body");
Log.d("test", "TEST ID" + body1);
pushNotification(notifText);
} catch (Exception e) {
e.printStackTrace();
Log.d("test", "PUSH CATCH" + e);
}
}
Here are my logs
**2019-01-07 14:17:42.778 19712-19712/ibm.gekon.vasileiosvlachakis.gekon D/alekos:
response{"status":"success","message":null,"data":{"22":{"id":"22","created":"2019-01-07
14:11:55","createdby":158,"touched":"2019-01-07
14:11:55","touchedby":158,"start":"2019-01-07","end":"2019-01-08","scoperole":3,"scopecorp":1,"body":"test22</p>","language":"en"}},"error":0,"line":1515,"debug":null}
2019-01-07 14:17:42.785 19712-19712/ibm.gekon.vasileiosvlachakis.gekon
D/alekos: PUSH CATCHorg.json.JSONException: Value data of type
java.lang.String cannot be converted to JSONObject**
Here you can get the value of body key. but this is specific for 19 and 20 JSON object
JSONObject dataObj = new
JSONObject(sb.toString()).getJSONObject("data");
JSONObject dataObj19 =dataObj.getJSONObject("19");
String body1 =dataObj19.getString("body");
JSONObject dataObj20 =dataObj.getJSONObject("20");
String body2 =dataObj20.getString("body");
if Response has multiple JSON object inside data JSON object then you need a loop to retrieve it
JSONObject dataObj =new JSONObject("data");
for(int i=0;i<dataObj.length();i++){
JSONObject data =dataObj.getJSONObject(i);
String body =data .getString("body");
}
JSONObject json = new JSONObject(sb.toString());
String statistics = json.getString("data");
for(Iteraor key=json.keys();key.hasNext();) {
JSONObject keyValue = json.get(key.next());
//now keyValue contains the 19,20 and so on...
String body1 =keyValue.getString("body");
Log.d("test", "TEST ID" + body1);
}
Try this it might work.
best way is to make static key, but you can get all keys and then get value for each one
use
JSONObject dataObj =new JSONObject("data");
Iterator<String> keys=dataObj.keys();
while (keys.hasNext())
{
JSONObject currentObject =dataObj.getJSONObject(keys.next());
String currentBody =currentObject.getString("body");
Log.d("test", "TEST ID" + currentBody);
}`
In JSON response your key should always be static in order to get a particular response from the key.
Here check whether your data JSONObject contains that key or not for error handling.
try {
JSONObject jsonObj = new JSONObject(sb.toString());// assuming this as your main JSONObject
if(jsonObj.has("data")){
JSONObject dataObj =jsonObj.getJSONObject("data");
if(dataObj.has("19")){
JSONObject json19 = dataObj.getJSONObject("19");
// Now here check if the json19 contains the key that you want.
if(json19.has("body")){
String valueBody = json19.getString("body"); // this will give you the value of body
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Poorly formatted json parsing

I use code above to parse JSON in a try-catch.
JSONArray jsonRootObject = new JSONArray(text);
JSONArray jsonArray = jsonRootObject.optJSONArray(2);
name = jsonArray.toString();
Toast.makeText(MainActivity.this, name, Toast.LENGTH_LONG).show();
I use 2 as index in code below, because I would get values from candidates. I think, that is strange, because there isn't key-value pairs in array. I would like to get only the first key from this array (In this example subtest1.), its value isn't make sense.
{
"images": [
{
"time": 2.86091,
"transaction":
{
"status": "Complete",
"subject": "test2",
"confidence": 0.77,
"gallery_name": "gallerytest1",
},
"candidates": [
{
"subtest1": "0.802138030529022",
"enrollment_timestamp": "1416850761"
},
{
"elizabeth": "0.802138030529022",
"enrollment_timestamp": "1417207485"
},
{
"elizabeth": "0.777253568172455",
"enrollment_timestamp": "1416518415"
},
{
"elizabeth": "0.777253568172455",
"enrollment_timestamp": "1416431816"
}
]
} ]
}
Try this and see if it solves your problem
JSONArray CandidatesArr = new JSONArray(jsonRootObject.getString("candidates"));
JSONObject CandidatesOBJ = CandidatesArr.getJSONObject(0);
String name=CandidatesOBJ.getString("subtest1");
Edit
To check if your key subset1 exists or not try the following code:
String name=""
if(CandidatesOBJ.has("subtest1")){
name=CandidatesOBJ.getString("subtest1");
}
your parser should be like.FYI JSONArray does not have key-value pairs but JSONObject does.
JSONObject root = new JSONObject(text);
JSONArray jarray = root.optJSONArray("images);
if(jarray != null){
JSONObject jObject = jarray.optJSONObject(0);
if(jObject != null){
JSONArray candidates = jObject.optJSONArray("candidates");
JSONObject jObj = jarray.optJSONObject(0);
if(jObj != null){
String subTest = jObj.optString("subtest1");
}
}
}

Nesting a multiple jsonobjects within a json array

Im trying to create a json array using the following code.
private JSONArray getJsonArray(String encodedString) {
JSONArray docArray = new JSONArray();
JSONObject docprops = new JSONObject();
JSONObject innerJson = new JSONObject();
JSONArray innerJsonArray = new JSONArray();
JSONObject inJobj = new JSONObject();
JSONArray outerJsonArray = new JSONArray();
SharedPreferences userDetails = getSharedPreferences("userdetails", Context.MODE_PRIVATE);
String session = userDetails.getString("session", "");
try {
innerJson.put("compliance_history_id", compliance_history_id);
docprops.put("file_size", fileSize);
docprops.put("file_name", fileName);
docprops.put("file_content", encodedString);
docArray.put(docprops);
innerJson.put("documents", docArray);
innerJson.put("completion_date", mCompletedDate.getText().toString());
innerJson.put("validity_date", JSONObject.NULL);
innerJson.put("next_due_date", mNextDueDate.getText().toString());
innerJson.put("remarks", mRemarks.getText().toString());
innerJsonArray.put("UpdateComplianceDetail");
innerJsonArray.put(innerJson);
inJobj.put("session_token", session);
inJobj.put("request", innerJsonArray);
outerJsonArray.put(session);
outerJsonArray.put(inJobj);
} catch (JSONException e) {
e.printStackTrace();
}
return outerJsonArray;
}
This is the json that my code is framing up..
[
"1-e4077f4a346440ecaeaf5f3387d47775",
{
"request": [
"UpdateComplianceDetail",
{
"remarks": "Remarks",
"next_due_date": "27-Mar-2016",
"completion_date": "31-may-2017",
"validity_date": null,
"documents": [
{
"file_name": "20160404_135811.jpg",
"file_size": 24,
"file_content": "iVBORw0KGgoAAAANSUhEUgAAABIAAAASCAQAAAD8x0bcAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mA"
}
],
"compliance_history_id": 49
}
],
"session_token": "1-e4077f4a346440ecaeaf5f3387d47775"
}
]
There might be multiple documents that are being uploaded so document array might contain multiple json objects within it. How can I be able to do so?
Is there by any means through which I can optimize the above code other than by using gson or jackson?
If documents is an array, iterate through the JSONArray object
JSONArray jsonObjectArray= updateComplianceDetailresponse.getJSONArray("documents");
LinkedList arrayCompliance=new LinkedList();
for(int count=0;count<jsonObjectArray.length();count++){
// iterate and get required elements
//Add to arrayCompliance LinkedList
}
If you might have multiple objects inside docArray then the below lines should be inside a for loop.
JSONObject docprops = new JSONObject();
docprops.put("file_size", fileSize);
docprops.put("file_name", fileName);
docprops.put("file_content", encodedString);
docArray.put(docprops);
SO depending on number of document objects you can iterate throught the for loop and for each iteration create a jsonObject and put it inside the docArray

How to process Json array in android without square bracket

Raw Json Data
[
{
"worker.1":{
"last_share":1443639029,
"score":"3722204.62578",
"alive":true,
"shares":1124332,
"hashrate":1047253
},
"worker.2":{
"last_share":1443639029,
"score":"3794755.69049",
"alive":true,
"shares":1069332,
"hashrate":1012070
},
"worker.3":{
"last_share":1440778690,
"score":"0.0",
"alive":false,
"shares":0,
"hashrate":0
},
"worker.4":{
"last_share":1443638222,
"score":"940190.67723",
"alive":true,
"shares":449932,
"hashrate":404772
}
"worker.nth":{
"last_share":1443638222,
"score":"940190.67723",
"alive":true,
"shares":449932,
"hashrate":404772
}
}
]
From the main question I have been able to narrow down the results and managed to add the Square bracket as well. Now i have a Json Array above so could someone advise me how can i process this Json array. Also note that it can end up being 1000 workers.
Please please help I have been breaking my head for 2 days on this,
Also note that the actual Json data is complex and 1000's of entries,
The json data included is just an overview.
Edit: Code that I ma using to process the above Json
try{
JSONArray jArray = new JSONArray(jsonObj.getJSONObject("workers"));
if(jArray.length() == 0){
Log.d("Json Err", "JSON string has no entries");
return null;
}
JSONObject jObject = jArray.getJSONObject(0);
// To get one specific element:
JSONObject worker1 = jObject.getJSONObject("worker.1");
JSONObject worker2 = jObject.getJSONObject("worker.2");
// Iterate over all elements
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ) {
String key = (String)keys.next(); // "worker.1", etc
if ( jObject.get(key) instanceof JSONObject ) {
JSONObject entry = jObject.getJSONObject(key);
// Do something with your entry here like:
String score = entry.optString("score", "");
Boolean alive = entry.optBoolean("alive", false);
Integer shares = entry.optInt("shares", 0);
Log.d("Json Success", score );
}
}
} catch (JSONException e){
Log.e("Json Err", "Failure converting JSON String", e);
}
Error that I am getting:
E2570 (5:10 PM):
org.json.JSONException: Value {"worker.1":{"last_share":1443694390,"score":"15.6018529132","alive":true,"shares":59880,"hashrate":0},"worker.2":{"last_share":1443694180,"score":"2.97304689833","alive":true,"shares":2048,"hashrate":0},"worker.3":{"last_share":1440778690,"score":"0.0","alive":false,"shares":0,"hashrate":0},"ivonme.ant4":{"last_share":1443701343,"score":"8688.78118933","alive":true,"shares":203088,"hashrate":78633}}
of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java)
at org.json.JSONArray.(JSONArray.java)
at org.json.JSONArray.(JSONArray.java)
So you have...
{ //JSONObject
"worker.1":{
"last_share":1443639029,
"score":"3722204.62578",
"alive":true,
"shares":1124332,
"hashrate":1047253
},
"worker.2":{
"last_share":1443639029,
"score":"3794755.69049",
"alive":true,
"shares":1069332,
"hashrate":1012070
} //,...
}
To get all your workers you have to...
try{
JSONObject jObject = new JSONObject(yourStringFromYourQuestion);
// To get one specific element:
JSONObject worker1 = jObject.getJSONObject("worker.1");
JSONObject worker2 = jObject.getJSONObject("worker.2");
// Iterate over all elements
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ) {
String key = (String)keys.next(); // "worker.1", etc
if ( jObject.get(key) instanceof JSONObject ) {
JSONObject entry = jObject.getJSONObject(key);
// Do something with your entry here like:
String score = entry.optString("score", "");
Boolean alive = entry.optBoolean("alive", false);
Integer shares = entry.optInteger("shares", 0);
}
}
} catch (JSONException e){
Log.e(LOG_TAG, "Failure converting JSON String", e);
}
Try this:
JSONArray jArray=jsonObj.getJSONArray("workers");
instead of
JSONArray jArray = new JSONArray(jsonObj.getJSONObject("workers"));
The error is because of you are getting json array as object. I think so.

how to build Below kind of JSON Format to post it as a request in android?

Ineed to post data in JSON format as shown below And the size of the array is not
constant. it depends on the user.
{
"info": [
{
"Name": "foo1",
"Number": 123
},
{
"Name": "foo2",
"Number": 124
},
{
"Name": "foo2",
"Number": 125
}
]
}
I tried to create in the following way
JSONObject parent = new JSONObject();
JSONArray jArray = new JSONArray();
JSONObject childObj = new JSONObject();
childObj.put("Name", etName.getText()).toString();
childObj.put("Number", etNumber.getText()).toString();
jArray.put(childObj);
parent.put("info",jArray);
but i'm unable to get it and I also tried in this way like example 6.1 but there is no method like add for JSONArray. So how can post my data. Please help me.
Thanks.
I'm not sure exactly what your question is but I'd typically do something like this to create the JSON string that you are looking for (the example below is using the org.json reference implementation from http://www.json.org/java/index.html):
JSONObject parent = new JSONObject();
JSONArray infoArray = new JSONArray();
for(int i = 0; i < SOMEARRAY.length; i++)
{
JSONObject childObj = new JSONObject();
childObj.put("Name", etName.getText());
childObj.put("Number", etNumber.getText());
infoArray.put(childObj);
}
parent.put("info", infoArray);
String encodedJsonString = parent.toString();
I don't understand why you're calling toString() after putting stuff into childObj.
Anyway, this code should work:
JSONObject parent = new JSONObject();
JSONArray jArray = new JSONArray();
JSONObject childObj = new JSONObject();
try
{
//create first child
childObj
.put("Name", "foo1")
.put("Number", 123);
//insert it into the array
jArray.put(childObj);
//... repeat for all remaining elements
//attach the array to the parent
parent.put("info",jArray);
}
catch (JSONException e)
{
e.printStackTrace();
}
Then, to get your JSON as a string for POSTing just call parent.toString();

Categories

Resources