How to correctly generate Json without Backslashes - java

Problem:
I get json with backslashes as response from a GET Request
#RequestMapping(value = "repuve/recibe_captcha", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
like this:
{"mensaje":"Proceso ejecutado correctamente.","folio":"1652989601959","resultado":"{\"idSalida\":1,\"descSalida\":\"Proceso Correcto\",\"data\":[.....]}"}
When expected Result is like this:
{"mensaje":"Proceso ejecutado correctamente.","folio":"1652989601959","resultado":"{"idSalida":1,"descSalida":"Proceso Correcto","data":[.....]}"}
(The data array has a b64 image).
This is how json is created:
JSONObject object = new JSONObject();
JSONArray jArray = new JSONArray();
object.put("idSalida", 1);
object.put("descSalida", "Proceso Correcto");
jArray.put(captcha);
object.put("data", jArray);
I've tried some answers from StackOverflow using replace() but none of them seems to work for me.
Is there another way to remove the backslashes and get the correct json format delivered to front?
Thank you.

Any JSON generating framework should actually escape the nested quotation marks. If you expect the string to look differently, you will have write code that assembles that JSONary string the way you want.

Related

java org.json not supporting special characters like \uf4f8 ,\uf389\uf60d \u2026 emojis)

I have java string like below and I am trying to convert to JSONArray using org.json library.
String content = "[{ \"message\":\"This year\\u2019s #SexiestManAlive goes to #chrisevans \\uf389\\uf60d \\u2026they did this one for us \\uf979\\n(\\uf4f8: #mschwartzphoto x #people )\"}]"
JSONArray jsonArray = new JSONArray(content);
When I am converting this to JSONArray some extends emojis are not converting (\uf4f8 ,\uf389\uf60d \u2026". )
it looks like this after converting this msg to jsonarray
"This year’s #SexiestManAlive goes to #chrisevans  …they did this one for us 凉\n(: #mschwartzphoto x #people )"
How can we handle this  ? please need help on this.
For Reference:: actually text message in API looks like this
This year’s #SexiestManAlive goes to #chrisevans 🎉😍 …they did this one for us 🥹
(📸: #mschwartzphoto x #people )

Issue in passing string in Request Body

I am facing an issue while making a request body to do an API call in Java.
Required Body
{
"id" : [1,2]
}
I have an integer array with me lets say arr, I am creating the request something like:-
JSONObject jsonObject = new JSONObject();
jsonObject.put("id",Arrays.toString(arr));
String stringBody = jsonObject.toJSONString();
RequestSpecification specification = RestAssured.with();
specification.body(stringBody);
Response response = specification.post(endpoint);
What it actually does is make the request body as something like below.
{
"id" : "[1,2]"
}
As it sends the value as String so my server throws an error, Expected a list of items but got type \"unicode\".
Can somebody help me in here. How do I send it in raw format instead of String.
Use
jsonObject.put("id",Arrays.asList(arr));
to build the json body.

Conversion of JSON to XML

I am converting JSON Values to XML. Instead of getting JSON properties as elements of XML I am getting "title":"source". The output I wanted is <title>source</title>. What is the mistake I am doing? I am writing this code in JavaScript function.
I am using x2js plugin for conversion and I have included it using script tag.
My code to convert dynatree to JSON and JSON to XML is:
var x2js = new X2JS();
var tree = $("#source").dynatree("getTree").toDict();
alert(" tree:"+tree);
var jsonObject = JSON.stringify(tree);//dynatree to JSON
alert(" jsonObject :"+jsonObject);
var xmlAsStr = x2js.json2xml_str( jsonObject );//JSON to XML
alert("xml "+xmlAsStr);
Try to not use JSON.stringify(tree); this escapes the string.
Set var xmlAsStr = x2js.json2xml_str(tree);

JSON parsing No value

Im not sure whats the error behind this, but im getting an error saying
org.json.JSONException: No value for
http://starstrakph.s3.amazonaws.com/12/avatars/1386757806.jpg
My JSON are as follows
{"id":"12","display_name":"Anne","screen_name":"Anne Curtis","avatar":"http:\/\/starstrakph.s3.amazonaws.com\/12\/avatars\/1386757806.jpg","avatar_source":"http:\/\/www.balita.com\/filipino-superstar-anne-curtis-katulong-ng-pechanga-resort-casino-sa-pagdiriwang-ng-araw-ng-kasarinlan-ng-pilipinas\/"}
And my codes are:
JSONObject userObj = new JSONObject(result);
cFeeds.SetPostScreenName(userObj.getString("screen_name"));
String avatar = userObj.getString(userObj.optString("avatar"));
cFeeds.SetAvatar(avatar);
Should I use JSON array for this? is there any wrong on my code or am i missing something?
Thanks in advance
The problem is that you are using the value of the json object (which is a json String) named avatar as the name of another json object which obviously doesn't exist.
String avatar = userObj.getString(userObj.optString("avatar"));
It seems you just want the value of avatar, so just get it
String avatar = userObj.optString("avatar");

JSON parsing. Unexpected character (t) at position 2. JAVA

I'm trying to parse JSON data from a google maps search.
I've tryed both JACKSON and and now I'm Trying JSON SIMPLE. Both of them gives the same error.
First of all I'm doing an search on Google maps.
String urlString = "http://maps.google.com/maps?f=q&source=s_q&output=json&start=0&q="+ "Stockholm" + "+Gym";
Gives me JSON while(1);{title:"stockholm Gym - Google Maps",url:"/maps?f=q\x26source=s_q\x26start=0\x26q=stockholm+Gym\x26ie=UTF8\x26hq=Gym.............. and so on.
I'm replacing the while(1); with ""; before i return the string.
To the problem when I'm trying to parse it
JSONParser parser = new JSONParser();
String jsonString = "";
// UriHandler.mapSearchJson is the method that returns the jsonString.
String jsonData = UriHandler.mapSearchJSON(jsonString);
Object obj = "";
try {
obj = parser.parse(jsonData);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject jsonObj = (JSONObject) obj;
String title = (String) jsonObj.get("title");
System.out.println(title);
This gives me the exception.
Unexpected character (t) at position 2.
When I'm debbuging it. comes all the way to when it's trying to parse the string. then the obj is = null.
What in thw world am I doing wrong.
Thanks!
As the others already mentioned, a nonquoted field name is not standard JSON. However, Jackson (and maybe others) has a set of option settings that allow it to work with nonstandard, but common JSON derivatives:
JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES
will enable processing of unquoted field names.
The response is not valid JSON, as the key name was not quoted with double quotes.
{title:"stockholm Gym"
is invalid JSON, it should be this:
{"title":"stockholm Gym"
Notice how title is surrounded by " double quotes
You are pulling back Javascript code that is meant for the maps.google.com site to use.
There could be any Javascript code in that response, not just the JSON that happens to be returned as part of the search.
You need to request from their maps API instead:
http://maps.googleapis.com/maps/api/geocode/json?address=Stockholm+Gym&sensor=false
This will return you only the JSON data.
Have a look the Google Maps API for more options.
I faced this error when trying to parse the json returned from kafka (kafka twitter producer).
The message returned was including some extra text other than json (KeyedMessage(twitter-test_english,null,null). Because of that I was facing this error.
KeyedMessage(twitter-test_english,null,null,{"created_at":"Sat Apr 23 18:31:10 +0000 2016","id":723942306777337856,"id_str":"723942306777337856"}
Pass only the message part from returned json and convert it into string.
{"created_at":"Sat Apr 23 18:31:10 +0000 2016","id":723942306777337856,"id_str":"723942306777337856"}
message = new KeyedMessage("twitter-test_english", (String)queue.take());
//System.out.println("This is message"+message.message());
String message_string = message.message().toString();
JsonParse.toParseJson(message_string);

Categories

Resources