Can't parse JSON array of objects - java

I have a NodeJS cloud function that takes a bunch of javascript objects (entries from a db) in the form of an array, and sends them to the client.
On the server I do this using:
return JSON.stringify(result);
Where "result" is the array of JS objects. Then I send data to the client.
In my Android client, I receive the String, and need to iterate through every object in the original array and process them separately. I can't! I always get errors like:
I: [Batch] com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected name at line 1 column 3 path $[0].
On my Android client, I have tried:
WebItemEntry [] items = new Gson().fromJson(jsonString, WebItemEntry[].class);
AND ...
ArrayList<WebItemEntry> items = new Gson().fromJson(jsonString, new TypeToken<ArrayList<WebItemEntry>>(){}.getType());
Neither seem to work. Same error as above.
The raw output I get from the database is the JSON string that consists of five individual entries that I would like to iterate through and parse. Its kind of a mess, but you can see its deliminator is the brace {. I really want to use GSON or similar in my android client to parse these entries individually and convert them to my custom Java class: WebItemEntry.
[{\"charityID\":0,\"purchaserZIP\":\"\",\"category\":\"Women\u0027s Accessories\",\"valueCents\":0}, {... same thing for a different entry here...}, {new entry ... }]

On the server ignore stringify and return plain object, those \" characters appear when js object stringify twice. so replace return JSON.stringify(result); with return result;.

Related

Getting a JSON Array from JSON Object (SOLVED)

First time having to work with JSON data on my own, even if very simple.
Here is the JSON data I'm working with:
{
"heart" : [92, 108],
"temperature" : [85.08, 85.66],
"conductance" : [4095, 4095]
}
What I'm attempting to do is extract one of the three arrays found within that JSON object, but I'm receiving a JSONException: Not a primitive array: class org.json.JSONArray. Here is a portion of the code that I'm using to extract the array of values associated with "heart":
JSONObject obj = new JSONObject(obtainJSONObject());
JSONArray arr = new JSONArray(obj.getJSONArray("heart")); // This is where the error is occuring
int low = arr.getInt(0);
int high = arr.getInt(1);
I've tried to follow what this solution answered, but can't really make much sense of it: How to Get JSON Array Within JSON Object?
I'm not sure if it has something to do with the way how the JSON data is being formatted? I did check online to see if it was any valid or not at https://jsonformatter.curiousconcept.com/. Any help or insights will be greatly appreciated!

How to send hashmap <Object,boolean> as a JSON to angular controller?

I am quite new to AngularJS. I am trying to send a hashmap over to angular controller through a REST service. I am using JSONContentEncapsulator for the same. I am not sure about the syntax.
JSONContentEncapsulator<HashMap> encapsulator = new JSONContentEncapsulator<HashMap>(sampleHashmap);
The problem is my Hashmap is sent over to controller with the object converted in the string format.
Also when I try printing the key value pair on the screen using ng-repeat, it's blank.
but when I print it in my controller using forEach I am able to see the values.
Could anyone please help as to how I should achieve this so that I can retrieve the object and corresponding boolean value on the screen?
EDIT1: The json values returned by REST service in my controller look like below:
{"EventValue(eventValueId=14, eventValueDescription=Deb Basic Neg Settle-intern plus , valueClassId=ALTBASIC, resultType=CALC, creditdebitIndicator=DEBIT, sign=POSITIVE, custAccountType=INTERNAL_SETTLEMENT)":true,"EventValue(eventValueId=11, eventValueDescription=Cred Basic Neg Correction minus , valueClassId=ALTBASIC, resultType=CORP, creditdebitIndicator=CREDIT, sign=NEGATIVE, custAccountType=NA)":true}
Where EvenValue is the object which is used as key and there is corresponding boolean value with it.
As I read online. It is not possible to send Map with Object as key in JSON format.
So instead I created two arraylists out of the map and sent those as a part of a single nested list.
It works fine.

javax.json produces uncomprehensible json

I have a Java class with two atrributes that I convert to json using this method. I followed this other answer:
Return JSONArray instead of JSONObject, Jersey JAX-RS
public String toString(){
// takes advantage of toString() implementation to format {"a":"b"}
JsonObject json = Json.createObjectBuilder()
.add("sentence", sentence)
.add( "category", category).build();
return json.toString();
}
The String I get is encapsulated into an ArrayList of strings, and sent via HTTP (I am using Jersey):
return Response.status(200).entity(response).build();
How ever, the node client is use cannot parse it properly: it gets the array part, accesses the elements perfectly. But not the json keys and values;
returns undefined:
jsonRespuesta = JSON.parse(body)[0];
console.log(jsonRespuesta);
console.log("Frase: " +jsonRespuesta.sentence + " ,Categoria: " + jsonRespuesta.category);
Returns:
{"sentence":"hola","category":"2"}
Frase: undefined ,Categoria: undefined
What's failing? If it helps, capturing the packets with wireshark displays the array members as strings
Is your java client encoding the JSON twice? I noticed you are adding json strings to an ArrayList, but you should really be adding objects to the ArrayList and then stringifying the whole thing once.
Try using JSON.parse() again on jsonRepuesta and see if that gets you what you're looking for. Alternatively, log out a typeof jsonRepuesta -- looks like it's still a string.
Also, see here.

Can't get JSONArray from .net web service

I have a multi-platform Cordova app backed by a .net web service which returns JSON data for syncing. This works fine.
I am now trying to add native calls into the Android version of the app which are hooked into BroadcastReceiver so that I can provide rich notifications when the app isn't running.
The scheduling and execution of these events are running fine; but I am having real problems in processing the result of the web service call.
The web service call (VB.net) is:
<OperationContract()>
<WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json)>
Public Function SyncNotifications_Native(ByVal dateAfter As String, ByVal which As Integer, ByVal userID As Int32) As String
Dim rowsList As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object)
:::
:::
While dr.Read()
row = New Dictionary(Of String, Object)
row.Add("allow_reply", dr("allow_reply"))
row.Add("content", dr("content"))
row.Add("date_added", dr("date_added")
row.Add("date_deleted", dr("date_deleted")
row.Add("date_read", dr("date_read")
row.Add("deleted", dr("deleted"))
row.Add("last_update", Now().ToString("yyyy-MM-dd HH:mm:ss"))
row.Add("notification_id", dr("notification_id"))
row.Add("subject_line", dr("subject_line"))
row.Add("user_id", dr("user_id"))
rowsList.Add(row)
End While
Return New JavaScriptSerializer().Serialize(details)
End Function
This should return an array of zero or more entries.
I'm using an AsyncTask to get the data. This is the data I get back from the call:
{"d":"
[{\"allow_reply\":1,\"content\":\"test content\",
\"date_added\":\"2016-02-04 23:37:50\",\"date_deleted\":\"\",
\"date_read\":\"\",\"deleted\":0,\"last_update\":\"2016-02-04 23:38:43\",
\"notification_id\":27,\"subject_line\":\"test\",\"user_id\":1}]
"}
I've looked at various resources and have tried all types of solutions. This is what I'm currently doing:
Convert the return string to a JSON Object:
JSONObject json2 = new JSONObject(s);
Try to get the array out of the object:
JSONArray results = json2.getJSONArray("d");
This way gives me an error of:
java.lang.String cannot be converted to JSONArray
I've seen a suggestion in another post that I'm actually returning a SOAP response from my web service; I'm not sure, I haven't seen any other example JSON responses which start with
{"d":
How can I properly get the returned array into a JSONArray so that I can pass it off to another function?
Thanks
Am not a Java dev so:
{"d": "[{\"allow_reply\":1,\....."} is an Object
with a d field
whose value is a string "[{\"allow_reply\":1,\....."} and is why you get java.lang.String cannot be converted to JSONArray
so you'll have to parse (aka "deserialize")
So in Javascript (you'll have to translate to Java):
//this is the data your service returns
var foo = {"d": "[{\"allow_reply\":1,\"content\":\"test content\",\"date_added\":\"2016-02-04 23:37:50\",\"date_deleted\":\"\",\"date_read\":\"\", \"deleted\":0,\"last_update\":\"2016-02-04 23:38:43\",\"notification_id\":27,\"subject_line\":\"test\",\"user_id\":1}]"};
//parse the string
var data = JSON.parse(foo.d);
data now contains your array
So in your code above, you have to parse the string and convert it into the object it represents (from a string).
Hth...

I would like to see an example web method that passes an array of objects from aspx webservice

im trying to self learn how to consume an aspx web service from android.
In this case im trying to pass an array of objects from a web service.
I would like to take a look at a sample [web method] that passes an array of objects.
and if possible a sample code of how the array passed by the web service is consumed by the android application. (the java code)
Any code posted would be highly appreciated.. Thanks in advance!
You will have to use JSON to get array of objects in Android
so Now, let me start to give step by step demo for parsing the same JSON resoponse:
Step – 1:
create a JSONObject with the received response string:
JSONObject jsonObject = new JSONObject(strJSONResponse);
Step – 2:
Get the main object from the created json object by using getJSONObject() method:
JSONObject object = jsonObject.getJSONObject("FirstObject");
Step – 3:
Now this FirstObject contains 2 strings namely “attr1″,”attr2″ and a object namely “sub”.
So get 2 strings by using getString() method.
String attr1 = object.getString("attr1");
String attr2 = object.getString("attr2");
and get a sub object by using the same getJSONObject() method as we have used above:
JSONObject subObject = object.getJSONObject("sub");
Step – 4:
Now this “sub” sub-object contains 1 array namely “sub1″. So we can get this JSON array by using
getJSONArray() method:
JSONArray subArray = subObject.getJSONArray("sub1");
Now, we just need to process this array same as simple string array:
for(int i=0; i<subArray.length(); i++)
{
strParsedValue+="\n"+subArray.getJSONObject(i).getString("sub1_attr").toString();
}

Categories

Resources