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.
I'm trying to get a value from an XML response using REST Assured, but I'm only getting empty values.
XML example:
<?xml version="1.0" ?>
<ncresponse
orderID="50143601"
STATUS="5"
SCORING="1"
SCO_CATEGORY="G">
</ncresponse>
My code:
RestAssured.useRelaxedHTTPSValidation();
Map<String, String> body = new HashMap<>();
body.put("ORDERID", orderId);
body.put("USERID", QUERY.getUser());
body.put("PSW", QUERY.getPass());
Response validation = given().proxy(host("myproxy.com").withPort(8080)
).params(body).when().get(QUERY.getUrl());
return from(validation.asString()).get("ncresponse.STATUS");
In this case, I'm trying to get the STATUS value ("5"), but all I'm getting is "" for any attribute.
Any help would be very appreciated.
You need to first convert the response to xml type and then get the value from that response.
First you need to import the following in your code:
import io.restassured.path.xml.XmlPath;
And then your code should be:
String stringResponse = validation.asString();
XmlPath xmlPath = new XmlPath(stringResponse);
String status = xmlPath.get("ncresponse.STATUS");
Now the String status contains the value which you want.
Well, i realized that I was making a mistake here. I was trying to get an attribute from the node "ncresponse", so using "#" symbol before the attribute is neccesary:
from(validation.asString()).get("ncresponse.#STATUS");
Im closing this, thanks for all!
I need to turn a full string into Json format, the challenge is that within the payload there is a nested field which requires be read as Json likewise.
My java code look like:
First I read the string :
String payload
="{\"appId\":\"APP02\",\"employeeId\":\"789-33-3887\",\"name\":\"Paolo Ledner\",\"phonenumber\":\"757.910.0396\",\"beer\":\"Sierra Nevada Bigfoot Barleywine Style Ale\",\"company\":\"Schmidt LLC\",\"address\":\"{\\\"street\\\":\\\"Coralie Trafficway\\\",\\\"zipcode\\\":\\\"12291\\\"}\"}";
Now I read my first JSON object:
Gson g = new Gson();
JsonElement jelem = g.fromJson(payload,JsonElement.class);
JsonObject jobj = jelem.getAsJsonObject();
This return properly the Json object but I can't read the keys from the nested field address, then I need to read the content of this field , turn it into string and according to my logic then apply the same approach to get the Json format and read the keys I need, here is this step:
String address = jobj.get("address").toString().substring(1,jobj.get("address").toString().length()-1);
JsonElement jeaddress = g.fromJson(address, JsonElement.class);
JsonObject jaddress = jeaddress.getAsJsonObject();
System.out.println(jaddress.get("zipcode"));
Issues:
The string address returns properly {\"street\":\"Coralie Trafficway\",\"zipcode\":\"12291\"} but then when I try to print jaddress.zipcode I get the error:
Exception in thread "main" com.google.gson.JsonSyntaxException:
com.google.gson.stream.MalformedJsonException: Expected name at line 1
column 2 path $. at com.google.gson.Gson.fromJson(Gson.java:902) at
com.google.gson.Gson.fromJson(Gson.java:852) at
com.google.gson.Gson.fromJson(Gson.java:801) at
com.google.gson.Gson.fromJson(Gson.java:773) at
bncingestion.kafkaconsumer.validating_payload(kafkaconsumer.java:29)
at bncingestion.kafkaconsumer.main(kafkaconsumer.java:15) Caused by:
com.google.gson.stream.MalformedJsonException: Expected name at line 1
column 2 path $. at
com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1559)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:513) at
com.google.gson.stream.JsonReader.hasNext(JsonReader.java:414) at
com.google.gson.internal.bind.TypeAdapters$29.read(TypeAdapters.java:738)
at
com.google.gson.internal.bind.TypeAdapters$29.read(TypeAdapters.java:714)
at
com.google.gson.internal.bind.TypeAdapters$35$1.read(TypeAdapters.java:910)
at com.google.gson.Gson.fromJson(Gson.java:887) ... 5 more
An additional version of this transformation wihtout remove the " is here :
String address = jobj.get("address").toString();
JsonElement jeaddress = g.fromJson(address, JsonElement.class);
JsonObject jaddress = jeaddress.getAsJsonObject();
System.out.println(jaddress.get("zipcode"));
In this case the error is:
Exception in thread "main" java.lang.IllegalStateException: Not a JSON
Object: "{\"street\":\"Coralie Trafficway\",\"zipcode\":\"12291\"}"
at com.google.gson.JsonElement.getAsJsonObject(JsonElement.java:90)
at
bncingestion.kafkaconsumer.validating_payload(kafkaconsumer.java:31)
at bncingestion.kafkaconsumer.main(kafkaconsumer.java:15)
I appreciate any help.
thanks
Calling jobj.get("address").toString() formats the value (a JsonElement) as JSON, and since the value is a String, it adds quotes and escapes the content. Don't do that, i.e. don't call toString(), explicitly or implicitly, if you're after the value.
Replace line with String address = jobj.get("address").getAsString();
Also replace line with System.out.println(jaddress.get("zipcode").getAsString());
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);
Im trying to do the following:
UserFunctions uf = new UserFunctions();
JSONArray json = uf.getAllFreebies();
System.out.println(json + "blah1"); //Here im able to retrieve the whole JSONArray.
try{
System.out.println("1");
for (int i = 1; i <json.length(); i++) {
System.out.println("2");
jo = json.optJSONObject(i); //Im getting null value here
System.out.println(jo + "blah2"); //Here im getting null
...}
Im printing out my JSONArray using following lines.
JSONArray json = uf.getAllFreebies();
System.out.println(json + "blah1");
Now on the following lines when i tried to retrieve the JSONObject from the JSONArray and tried to print it out,it prints out "null" instead of the JSONObject at the particular index.
jo = json.optJSONObject(i);
System.out.println(jo + "blah2");
Can anyone pls tell me what am i doing wrong?I mean how can i get a null for JSONOBject when my JSONArray is not null?
Thank You.
Following is my JSONArray logcat:
05-31 21:02:57.156: I/System.out(318): [["viking","Art","Potrait","Potrait","Good","im giving out potrait 7325697","176 Fiat Ave","Iselin","New Jersey","USA","08830","2012-05-27"],["n00b","Books","Novels","Novels","Good","Im giving out novels 7325697","b9 maa krupa","petlad","Gujarat","India","388450","2012-05-27"],["n00b","Computers","laptop","laptop giveaway","Good","Im giving out laptop if you are interested than pls call on 7325697","B9 Ma Krupa","Petlad","Gujarat","India","388450","2012-05-27"],["mista","Cameras & Photos","Camera","Camera GiveAway","Very good","im giving out camera .its kodak .pls email me on mista#gmail.com","Mista Lee elm street","seoul","Korea","South Korea","ha8 9sd","2012-05-27"],["panda","Gaming Consoles","XBOX","XBOX 360","Very Good","Im giving out xbox 360.if you are interested please email me on panda#gmail.com","435 Carmen Rd,","Buffalo","New York","USA","14226","2012-05-27"],["viking","Cameras & Photos","Camera","Kodak Camera","Good","Kodak Camera giveaway.Pls call on 732397","","Iselin","New Jersey","USA","08830","2012-05-28"],["viking","Books","Novels","Novel GA","Good","Novel give away.call on 7325697.","","Iselin","New Jersey","USA","08830","2012-05-28"],["viking","Automotive","Car","Car GiveAway","Good","Im giving out car.if you are interested pls call 7323697.","176 Fiat Ave","Iselin","New Jersey","USA","08830","2012-05-29"],["viking","Collectibles","Medallions","Medallion GA","Very Good","Im giving out medallion.if inetrested pls call 732697","176 Fiat Ave,","Iselin","New Jersey","USA","08830","2012-05-29"],["viking","Clothing & Accessories","cloths","cloths giveaway","Good","im giving out cloths if you are interested pls call on 735697","176 Fiat Ave,","Iselin","New jersey","USA","08830","2012-05-29"],["viking","Books","Novel","Novel GA","Good","pls call 735697","435 carmen rd","buffalo","ny","usa","14226","2012-05-29"],["viking","Books","TextBook","CHemistry 101","GOod","pls call 735697","176 fiat ave","iselin","new jersey","usa","08830","2012-05-29"],["mista","Books","Notebook","Notbook","Good","im giving out notebbok if you are interested pls call 48374288423","elm street","seaoul","na","South Korea","jfjafjk","2012-05-29"]]blah1
logcat output when trying to print out JSONOBject at index i
05-31 21:02:57.156: I/System.out(318): nullblah2
The JSON [[...], [...], [...]] does not contain JSON-objects, but it does have some JSON-arrays.
Thus optJSONObject finds a JSON-array (where it expected a JSON-object) and returns null because it is of the incorrect type. (opt is short for optional.)
Use optJSONArray (note Array and not Object). Alternatively, use getJSONArray, which will throw a JSONException on failure.
Happy coding.
Note that JSON keeps a strict distinction between Objects, Arrays, and the various Values. The concept of an Array being a special (sub)kind of Object (in the JSON sense) exists in JavaScript but does not necessarily extend to other JSON implementations. For instance, the JSONArray class has no relationship with the JSONObject class.