can not parse json array from php - java

my array returns the following valid json.
{"usernames ":["a","b","c"]}
In Java I am trying to retrieve the value of the array by the following method. However I fail.
JSONArray usernames = json.getJSONArray("usernames");

The key ends with a space. try
JSONArray usernames = json.getJSONArray("usernames ");
EDIT:
It would be better to lose the space in your php script.

remove the space in your code : "usernames " ---> "usernames"

Related

Read a Java array in Javascript

I've a method that returns a 2d-array in java : public Object[][] getArray1() {}
I used println() to print it's content and i see that its well created.
On Javascript i assign this array to a var:
var content ="#{BDEStats.getArray1()}";
But i dont seem able to acess it's data. it always returns java.Lang.object; #... How can i do to display the content this array holds?
I've tried to cycle the array but i dont know how to refer to the objects it is holding. if i use content[1] to returns a char in that índex..! Kinda lost here
I think you may convert the array to JSON format before assigning it to javascript.
You can use some JSON framework to do this convert like:
JSON-lib
Jackson
Here a tiny Jackson demo:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
...
public static void main(String[] args) throws JsonProcessingException {
String[][] data = new String[1][2];
data[0][0] = "abc";
data[0][1] = "def";
System.out.println(new ObjectMapper().writeValueAsString(data));
}
This is the normal array String representation in Java, consisting in:
A number of [ based on the dimension
Either a letter for the primitive type (i.e. I for int), or L[fully qualified class name] for Objects
#
The array's hash code
For one-dimensional arrays, use java.util.Arrays.toString(myArray).
For multi-dimensional arrays, use java.util.Arrays.deepToString(myArray).
Edit (adding previous comment to answer)
You probably want to investigate JSON.parse to parse your Java array from JavaScript.
To turn a Java array into a string representation in a syntax which can be interpreted by a JavaScript engine, you need to turn it into the JavaScript Object Notation, or JSON for short.
There are many libraries available for Java to do this. Software recommendations are off-topic on Stackoverflow, but this article which compares 5 different libraries helped me to pick one for my project.
On the JavaScript side, you just have to use var content = JSON.parse(stringFromJava).
Or when you generate the JS code procedurally on the Java side, you can just embed the JSON string right into the sourcecode. This works because JSON is valid Javascript code for an object literal. In Java, this would look something like this:
scriptCode.append("var content = " + arrayAsJsonString + ";\n");
Ok problem solved. This was how I did it:
Instead of returning a Java Array I returned a JSON object in my method.
This JSON Object has a name and several other fields per ex:
(I'm getting my data from a Java List, so I iterate the list to populate the JSON object)
SONObject jsonObj = new JSONObject();
jsonObj.clear();
for (int tt=0; tamanho>tt ; tt++) {
try {
jsonObj.put("aa"+tt, ListaJobStats.get(tt).getName());
jsonObj.put("bb"+tt , new BigDecimal(ListaJobStats.get(tt).getAge() ....
After this if I printOut the JSON object in java i get a string:
aa0: '1st name'; aa1: ' 2nd name' ; bb0: 'age'; bb1: '2nd age' ... etc etc
After this in Javascript i get my JSON Object thorugh JSF like this:
var content=#{JAVACLASS.METHODTHATRETURNSJSON};
I stringify this object in JS:
var pars= JSON.stringify(content);
and i create the JSON object
var json = JSON.parse(pars)
Now I Iterate this JSON object in JS like this:
for (var tt=0; tamanho>tt ; tt++) {
[now im specifically adding the values to create a graphic but its just na exemple how u can acess te object]
data.setValue(tt, 0, json["aa"+tt]);
data.setValue(tt, 1, json["bb"+tt]);
...
Hope it will be useful. Take care

How to avoid the ‘\’ when appying JSONObject.put operation of two strings to a JSONObject?

The codes is like the following:
JSONObject solution = new JSONObject();
variableName = "TEST"
System.err.println("1:"+value);
solution.put(variableName, value);
System.err.println("2:"+solution);
Here is the output result:
1:{"min":10,"max":40}
2:{"TEST":"{\"min\":10,\"max\":40}"}
How can I get rid of the annoying '\'?
Thank you very much!
The reason why you are getting \ in your print line is because it is escaping the " character which is used in value. There's nothing wrong with this, it simply signifies that \" is not terminating the string and is instead a value part of that string.
Usage of double quotations is valid JSON, not single quotes - see related Q here.
But if you really want to, if you create value like this:
JSONObject value = new JSONObject("{'min':10,'max':40}");
Then you should get the desired output from your existing code:
1:{"min":10,"max":40}
2:{"TEST":{"min":10,"max":40}}

Parse serialized json payload in java

im struggling with json again :(
Here is the original response:
{"xml-fragment":{"workItem":{"#id":"251","#version":"74"},"presentation":{"#formIdenitifier":"1.0.0.201310151421/openspaceGWTPull_DefaultChannel/.default/Npda/NpdaProcess/UserReconcile/UserReconcile.gwt.json","#type":"GWT_FORM","#version":"1.0.0.201310151421","#activityName":"UserReconcile"},"workTypeDetail":{"#typePiled":"false","#pilingLimit":"0","#uid":"WT__RIoPEDWTEeOr4-yR8gXd7g","#version":"1.0.0.201310151421"},"payloadModel":{"serializedPayload":"{items:[{\"$param\":\"BankReconInput\",\"mode\":\"IN\",\"$value\":[{\"bankAccountTx_pk\":\"55213\",\"amount\":\"10099\",\"reference\":\"ImAmReference\",\"date\":\"2013-10-15\",\"reconType\":\"?\",\"amxcaseref\":\"pvm:0a12iq\",\"$type\":\"coza.npda.bom.BankTransaction\"}]}]}","#payloadMode":"JSON"}}}
i want to for example get value of amount from the serializedPayload. The problem is that it is not a json object. If i try:
obj = new JSONObject(jsonResp).getJSONObject("xml-fragment").getJSONObject("payloadModel");
this returns to me serializedPayload as a string and #payloadMode as a string.
i tried:
obj = new JSONObject(jsonResp).getJSONObject("xml-fragment").getJSONObject("payloadModel").getJSONObject("serializedPayload");
its confirms that serializedPayload is not a json object.
I looked at this example: http://developer.android.com/reference/org/json/JSONTokener.html
But its data is not as complex as mine and i am struggling to find java examples of how to do this.
Please can anyone help.
You don't need an example, you need to look at the JSON and think for a second.
serializedPayload is not a JSON object to begin with, it's really a string that has another piece of json encoded inside, sort of like the russian nesting dolls (frankly, it's an abomination).
You need to take the string, and then parse it again, using another JSONObject, sort of:
String payload = data..getJSONObject("xml-fragment").getJSONObject("payloadModel").getString("serializedPayload");
JSONObject theRealData = new JSONObject(payload);

Returning multiple sets of data using JSON with Java and JQuery

I want to send sets of data from servlet to the jsp using JSON. To elaborate, what exactly I want to do is take multiple rows from the database and print their values in jsp. I done with the part of DB connectivity and fetching of data. But I could not find a way to forward them to jsp using JSONObject. Each row has multiple attributes(column values). Please help me solve the problem.
What I'm doing is:
Collection <JsonObject> c=new ArrayList();
JsonObject j[] = null;
for(int i=0;i<uid_list.size();i++){//uid_list contains all the user_id's from the database
j[i].add("uid", j[i]);
j[i].add("fname", j[i]);
j[i].add("lname", j[i]);
j[i].addProperty("uid", uid_list.get(i).toString());
j[i].addProperty("fname", fname_list.get(i).toString());
j[i].addProperty("lname", lname_list.get(i).toString());
c.add(j[i]);
}
Also, is there any difference between JsonObject and JSONObject? The latter could not be recognized in servlet and by using JsonObject the put method is not recognized.
Aside from your code trying to insert into an uninitialized array, there are many JSON library for Java. You need to provide more details which one you're using
Also if your objective is just passing the JSON string into the browser, you might not even need jsp, you can just write the string version of the JSON object directly into the HttpResponse
Firstly, the JspnObject array has to be instantiated before it is used. Therefore, this means the following:
JsonObject j[] = new JsonObject[noOfObjects to be iterated]

How to create a JSONArray that contains Javascript code inside Java?

I am creating a JSONArray and parse it to a String, but as it even contains Strings instead of code it doesn't output as I need it.
for(Place place: places){
locations.put("new google.maps.LatLng("+place.getContactData().getLatitude()+","+place.getContactData().getLongitude()+")");
}
return locations.toString();
It outputs as: ["new google.maps.LatLng(53.5608,9.96357)","new google.maps.LatLng(53.5608,9.96357)"] but I need it without quotation marks like [new google.maps.LatLng(53.5608,9.96357),new google.maps.LatLng(53.5608,9.96357)] to be correctly interpreted by javascript.
Another method would be:
create an array with just the coordinates:
for(Place place: places){
JSONObject obj = new JSONObject();
obj.put("lat",place.getContactData().getLatitude());
obj.put("lng",place.getContactData().getLongitude());
locations.put(obj);
}
and then in javascript:
var places = (yourPlacesJson);
var placeObjects = [];
for(var i=0;i<places.length;i++)
{
placeObjects[placeObjects.length] = new google.maps.LatLng(places[i].lat,places[i].lng);
}
JSON only supports plain-old-data. It can't include any executable code (a new is executable code). This is by design - when JSON would be able to include executable code you would have to be much more carefully with importing JSON from an untrusted source.
All you can do is pass javascript code as strings and eval() it on the JS side after parsing the JSON.
Also you could use Regular expressions to remove the ", if you parse the json to another language
i had a similar problem, the way i made this work:
instead of writing the javascript before the json conversion, insert a placeholder.
locations.put("%mapsPlaceholder1%");
then after filling the array with placeholders, do:
locations.toString().replaceFirst("\"%mapsPlaceholder1%\"","yourJsCode");
something like that
you could also just create the array string manually

Categories