Parsing JSONObject in javascript or Jquery - java

Hi friends i have a java.util.Map object in Ajax method like this..
Map<String,List<String>> sm = new TreeMap<>();
List<String> str = new ArrayList<String>();
str.add("val1");
str.add("val2");
str.add("val3");
str.add("val4");
sm.put("shift1", str);
sm.put("shift2", str);
sm.put("shift3", str);
sm.put("shift4", str);
JSONObject json = new JSONObject(sm);
response.getWriter().print(json);
In run time Map elements will be increase or decrease
according to map elements I have to generate table
This is Ajax call.. I don't know how to parse that Map object and dynamically generate the table in javascript.
Please show me how.

I am just answering your question. I don't know java and also i don't understand the details you gave above. If I am wrong, I am sorry and kindly ignore it.
To parse the string to object
In the jQuery, $.parseJSON(string);
In js, JSON.parse(string);
I hope this will help U. Thanks.

var json = $.parseJSON( jsonString );
// This one wouldn't be supported in old browsers
json = JSON.parse( jsonString );
Additionally, you could, in Java, respond with the Content-Type application/json and then in the jQuery AJAX you will receive the JSON already parsed for you.
Of course this will not happen if you specifically configure your jQuery AJAX call to receive an plain text, or HTML, or other content-type response.
For more reference, see here, at the dataType setting.

Related

Send String to server without back slash

I am sending data (using Retrofit) to server like below way
"[\"emailaddress\"]"
But server need that data in below way
["emailaddress"]
I have tested in PostMan, only ["emailaddress"] works fine..
I have tried below code which is not giving me result what server wants.
var emailArray = "[\"$email\"]"
Can anyone help me how can i achieve that?
What should I need to change to make it as server wants?
Can you create json array object and put the content in it .. like below.
in Java this how you can acheive.
JSONArray postdata = new JSONArray();
postdata.put(<email address>);
and pass this to server by
postdata.toString();
So basically create array and push email to it, then while passing the data covert to string, that should work.
Escape the backslash in the regex.
Try this :
var emailArray = "[\"emailaddress\"]"
var emailArrayNew = emailArray.toString().replace("\\\\", "")
Could you try using List/ArrayList there?
val emailList = ArrayList<String>()
emailList.add("email1")
emailList.add("email2")
Then in Retrofit Api Service, do something like this
#Field("email") emailList:List<String>
Hope this will help you

JSON, Servlet and i18n

I am working on a back-end project where request is coming as JSON object to my servlet and response is sent as an JSON object as well. I found this LINK useful but need help to understand how filter can be used in my aforementioned back-end scenario to globalized my all classes/APIs through filter
I am new to Java and looking for advice that is it possible? OR I have to manually call ResourceBundle for each class
Thanks in anticipation
If you are receiving your i18n in json payload, you may try doing something as following
// this parses the json
JSONObject jObj = new JSONObject(request.getParameter("yourPramName"));
Iterator it = jObj.keys();
while(it.hasNext())
{
String key = it.next(); // get key
Object o = jObj.get(key); // get value
req.getSession().setAttribute(key, o);
}
Hope this helps.

Decode json object to string android

I used json_encode(); to convert string to json in php and then response it to android but I can't use the response, how can I convert the json to string?
when I display the response it shows this :
"{\n'OK': \n[\n{\n'Name': 'MyName',\n'Gender':'Male'\n}\n]\n}"
what shall I do?
thank you
Since you're just converting a string to json, you're not returning a JSONObject or JSONArray, according to: http://php.net/manual/en/function.json-decode.php
If you must return a string, you may have to use some json library or write your own parser.
If that doesn't sound appealing, I recommending returning a JSONObject or JSONArray with one element.
For example:
php
echo json_encode( array('result' => 'the string you are encoding') );
java
JSONObject json = new JSONObject( encodedStringResponseFromPhp );
String theStringYouEncoded = (String) json.get( "result" );
You'll need to add a throws JSONException to the function you add this java code too or put it inside a try catch block.
Have you tried using a JSON-Library like https://code.google.com/p/json-simple/? Looks like you need some help decoding the string.
Edit: You should use the json2.js library from Douglas Crockford. It provides some extra features and better/older browser support.
Read more...

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);

Display JSON Envelope on JSP

I have a Spring #Controller that is taking an existing ArrayList and creating a JSON envelope. When I display the JSON Envelope in the Spring Console, I see the data that I want is in there. When I view the same JSON Envelope in FireBug in Firefox, I also see the data that I want.
I'm attempting to display the envelop on the jsp page using JavaScript, and I really have no idea how to even start.
In other modules of the code, there are areas where it's getting information from a DataBase, using YUI2 to display it with a DataTable. It also uses a JSON Envelope, and it works. I'm trying to copy this to display just the JSON text string on the JSP page. I don't know if I need to use YUI2, or if I can just use JavaScript to access the JSON Envelope.
I am brand new to Java and JSON and the Spring environment, so I don't even have any idea what sort of JavaScript syntax to use to access the JSON Envelope, much less display it. I've been Googling to find an answer, but so far most of it is above my head.
I'd appreciate any help. Thanks.
Your Question is very unclear.
If you simply want to display the text of the JSON, then you don't need to use javascript at all. Just use <c:out> to output the JSON string into the relevant part of a plain HTML page.
You would use Javascript if you wanted to generate dynamic HTML on the client side. And at that point you'd probably want the Javascript to use an XMLHttpRequest object to call to the server to request the JSON. The Javascript would then be responsible for dynamically turning that JSON response into stuff that can be displayed ... and you'd definitely be wanting a client-side JS framework to help with that.
To parse the retrieved JSON you can use $each method of jQuery
var obj = {
"Name": "Robert",
"Counrty": "USA",
"Address" : {"Apartment":"111","City":"Atlanta","State":"GA","Zip":"30005" }
};
$.each( obj, function( key, value ) {
alert( key + ": " + value );
if(typeof(value)=="object")
{
$.each( value, function( key, value ) {
alert( key + ": " + value );
});
}
});
If you have more complex JSON then you have to repet $each for each complex type as I did for Address.
Then you can use the Key value to fetch the data from the JSON object.
Working example

Categories