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...
Related
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;.
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.
I'm having some troubles with different back-end processing of POST rest calls. I have two different objects which are updated through two different POST methods in my back-end. I catch the objects as a JsonNode, and in order to parse the attributes which I need to update, i create an iterator like so :
final Iterator<String> fieldNames = attributes.fieldNames();
The problem comes when I send my data from angular, in one case I need to explicitly send it like angular.toJson(data) in order to properly grab all the field names, and in the other case I just send the data (without the angular json conversion). Why is this behavior occurring ? Does this have to do with how I create the $http post call ? Here are the two different calls from angular:
$http.post(URL, angular.toJson(data)).success(function(data){
/*whatever*/ }).error(function(data) {
/*whatever*/ });
//Second call looks like this
var promise = $http({method: 'POST', url:URL, data:data, cache:'false'});
//this one i resolve using $q.all
I truncated the code to just the important stuff. My data is created like this currently(tried multiple ways in order to skip the need for toJson):
var data = "{\"Attribute1:\"+"\""+$scope.value1+"\","+
"\"Attribute2:\"+"\""+$scope.value2+"\"}";
How do I need to send the json data in order for it to correctly be converted to a JsonNode in my back-end, so I can properly iterate the fieldNames ?
I did manage to come to a common solution which consumes the json correctly in my back-end. I declared my json objects in angular like this :
$scope.dataToSend = {
"SomeAttribute" : "",
"SomeOtherAttribute" : ""
};
And then added my values like so :
$scope.dataTosend.SomeAttribute = someValue;
$scope.dataTosend.SomeOtherAttribute = someOtherValue;
No longer need to send the data with angular.toJson().
I'm trying to pass json data from javascript to java, like below. The idea is to pass the data to the java code as a javascript object (and not a a string which I know can be done ). I've tried the code below without success - idea was to use NativeJson.stringify to convert from a javascript object to a Java string, however this results in an Undefined instance instead of the expected string. Any idea on this could be achieved much appreciated.
in javascript file "test.js"
parser.fct ( {"abc":123,"def":456} )
in java
//1.binds javascript calls to Java
...
ScriptEngine engine = new ScriptEngine...
Bindings bindings = engine.createBindings();
bindings.put("parser", new Parser());
engine.eval("test.js");
//2. in Parser class
public void fct(Object obj){
Context ctx = Context.enter();
ScriptableObject scope = ctx.initStandardObjects();
Object json = NativeJSON.stringify(ctx, scope, obj, null,null);
//json returned is of type Undefined
}
Could not find a way to use NativeJSON.stringify(). I ended up building the json string "by hand", i.e Iterating on the property ids of the native javascript object and adding these properties to a java Map.
The Map is then transformed into a json object using new JSONObject(map);
link to source code
https://gist.github.com/eleco/c2bc77dca9ecc844a924
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();
}