How to parse Json object in ajax - java

I am not able to parse tje Json object returned from the servlet in ajax,
I need to put json object values in there relative field
From my java code i am sending the below String in the form of JSON
String webVisitorDetails = "{"+"companyName : \""+webVisitor.getCompanyName()+ "\","+
"address : \""+webVisitor.getProfessionalAddress()+ "\","+
"city : \""+webVisitor.getCity()+ "\","+
"zipCode : \""+webVisitor.getZipCode()+ "\","+
"clientId : \""+webVisitor.getCustomerAccountNumber()+ "\"}";
In ajax
$.ajax({
url: "ships",
data: {
email: email.toString()
},
success: function(data) {
$.each(data, function(k, v) {
console.log(k + " Value " + v);
$("#city").text(v.city);
$("#zipcode").text(v.getZipCode);
$("#Adress").text(v.getProfessionalAddress);
});
},
error: function(data) {
console.log("error:", data);
},
type: "post",
datatype:"json",
});

Note that the jQuery setting is dataType with a capital T. To do the JSON parsing manually, use the parseJSON function. However, if you set the Content-Type of your servlet response to application/json, the datatype should be auto-detected.
After you fixed this: Does it work? What is the value of the data argument of your success handler?
console.debug(data);
As Neal already said, JSON parsing expects valid JSON strings starting with jQuery 1.4. You can validate your JSON jsonlint.com.
In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
To avoid the manual building of JSON strings, use something like the JSON-java processor (from iNan's comment) or other Java implementations listed on json.org.

You json string is incorrect
The keys must be surrounded by double quotes.
Read the requirements here

If it's creating a problem because of the single-inverted comma ('), then just do:
jQuery.parseJSON(data.replace(/'/g, '"'))
If that is the case then it should work for you...

Related

Error tolerance of URI-encoded string syntax

I have picked up a legacy project and I am in the process of debugging something.
I have come across a custom JavaScript function (encodeJsonIntoString) which encode URI components for JavaScript object before sending over via AJAX.
The AJAX is nothing fancy:
$.ajax({
url: URL,
method: 'POST',
datatype : 'json',
data : encodeJsonIntoString(myObj),
success: ...
});
There is no custom processData or contentType set in the ajax call. What really puzzle me is why the previous developers didn't let $.ajax's data attribute to convert the JavaScript object automatically into a URI-encoded string or didn't even try using JQuery.param() to do it but to write the whole function themselves.
For a test, I have made a simple object to test the function encodeJsonIntoString:
var testDataA = {
list: [
{
lastname:"Smith",
firstname:"John"
},
{
lastname:"Black",
firstname:"Jack"
},
{
lastname:null,
firstname:"Mary"
}
]
};
After decoding URI components, the result of the function is:
list[0][lastname=Smith&list[0][firstname=John&
list[1][lastname=Black&list[1][firstname=Jack&
list[2][lastname=null&list[2][firstname=Mary
Notice there are lack of closing square brackets(]) in some places and it uses "null" for null values.
If I run JQuery.param() and decode it, I get this:
list[0][lastname]=Smith&list[0][firstname]=John&
list[1][lastname]=Black&list[1][firstname]=Jack&
list[2][lastname]=&list[2][firstname]=Mary
See the difference? But somehow the result of the function is accepted by the server(Java/Spring - #ModelAttribute) and read into the correct list structure.
I don't have access to the server side here, but I wonder if that array syntax is correctly acceptable or is it just "tolerated" by the server? Will the server see both versions of object in the same structure format?
I am tempted to just replace it with JQuery.param() to handle more robust input data in the future which may also accept special characters.

How do I remove all control characters in a string in Java?

My REST API, which is build with Spring in Java, produces an invalid JSON object, because it contains multiple breaks in a string, which lead to the problem, that the string has an unexpected end and the rest doesn't count as part of the string anymore, example:
{
"status": "Success",
"message": "Lorem ipsum",
"data": {
"correct": [
{
"record": "ULTRA LONG
XML STRING
WITH BREAKS",
"code": 0,
"errors": []
}
]
}
}
The error arises in the data -> correct -> record string field, because it contains breaks which splits the original string.
My API endpoint serializes the above JSON like this:
#PostMapping(value="/check-records",
consumes=MediaType.APPLICATION_JSON_VALUE,
produces=MediaType.APPLICATION_JSON_VALUE)
public Response checkRecords(#RequestBody(required=true) Records records) {
// Check records
return new Response("Success", "Lorem ipsum", data);
}
Response is a class, which automatically gets serialized into a JSON object after returning. data is a map in order to create the above JSON structure.
I couldn't find any suitable solution for my problem yet. Does anybody has an idea how I could remove all breaks, spaces or control characters before I serialize the JSON object?
I appreciate any kind of help, sheers! :)
Thanks to #pringi. He suggested to use a regex to remove all control characters in Java before I serialize the JSON object.
String record = orginalRecord.replaceAll("[\\\\p{Cntrl}^\\r\\n\\t]+", "")
You can find more informations about regex in the original question: How to remove control characters from java string?

Parsing a JSON component whose structure is always changing in JAVA

I want to extract all the keys and value from a JSON component. The issue is the structure of this is unknown. I want to parse it in JAVA such that I can retrieve any element using the key/field name.
For example:
In this CustomError object is in this format.
"CustomError": "{\"errors\": [{ \"type\": \"INVALID_HTTP_VERB\", \"description\": \"Invalid HTTP verb for the requested resource\" }]}"
In this its in this format.
"CustomError": "{\"status\":{\"code\":104050,\"user_message\":\"Method Not Allowed\",\"developer_message\":\"Invalid http method or method not allowed\"}}"
My goal is to get all the keys and its value.
For 1st example :-
type : INVALID_HTTP_VERB
description : Invalid HTTP verb for the requested resource
For 2nd example :-
code : 104050
user_message : Method Not Allowed
developer_message : Invalid http method or method not allowed
Are you using the Google gson library? If so you can use the JsonParser object like;
JsonElement j_element = new JsonParser().parse(YOUR_STRING);
Then you can step through the element in whatever form it's in, you can check types like element.IsJsonObject() or element.IsJsonArray() or whatever.
You can also turn the element into an object if is one, and do object.has("value") then if it is a JsonObject you can loop through the fields like;
for (Map.Entry<String, JsonElement> entry : YOUR_OBJECT.entrySet())
{
//do further bits
}

Return 2 variables from the servlet after ajax query

I post to my servlet via AJAX this:
$.ajax({
url: 'myServlet?action=Doeth',
type: 'post',
data: {machine: i, name: txt, status:status}, // i have initilized the values before
success: function (data) {
$('#fep').val(data);
}
});
back in my servlet I have:
if(jspAction.equals("Doeth")){
int status = Integer.parseInt(request.getParameter("status"));
int name = Integer.parseInt(request.getParameter("name"));
String machine = request.getParameter("machine");
//do some stuff and assign in 2 variables
//fep = "a value" and var2="some more"
response.getWriter().write(String.valueOf(fep));
}
So in success the following input is filled with the value fep
<input id="fep" class="form-control" name="fep" required>
If I want to return not only one value but 2 from the servlet (lets say the variable var2, how I do this? I tried
response.getWriter().write(String.valueOf(fep));
response.getWriter().write(String.valueOf(var2));
but it didn't work
A Servlet can't return multiple results. It's function is to handle an HTTP request and produce a single corresponding HTTP response.
If you need to pass data in the response, you need to choose an appropriate format and serialise it. The most common thing you can use, is JSON.
JSON is a text - based data format, that can represent complex objects and data structures. There is also a wide variety of libraries for working with it.

Get data from Http request in servlet

I am sendin post request from jquery like this :
$.ajax({
type: "POST",
url: "Save",
data: { conr: conr ,expiry : expiry,settings : settings}
inside servlet , i am able to get parameters (conr , expiry , settings)
but the problem is that
the settings parameter contains serialized form data : like this :
high=true&ci=false&title=qTip+as+Button+Menu&private=true&email=abc#google.com
I know that i can use string tokenizer to get data but i want to make sure that- if their is any simple way or not?
You could use the HttpComponents and let URLEncodedUtils parse it for you.
So you could just invoke URLEncodedUtils.parse(yourString,Charset.forName("UTF-8")) and you receive as return a List<NameValuePair> containing name and value associated elements. In this case something like: hight = "true", title = "qTip as Button Menu" and so on. And this all with the right decoded.
You can also use split on the settings string with "&" as a regex.

Categories

Resources