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());
Related
I have a Springboot application. I receive objects in JSON format containing strings and other nested objects and arrays. The nested objects might contain strings with commas, : and /. I get an error when I pass objects containing commas, : and / in their strings.
I understand those characters are used for parsing JSON objects and therefore when included in the strings they can mess up the conversion. Is there a way to deal with that?
My code:
public String setProperties(#RequestBody Map<String, Object> body) throws JSONException {
logger.info("->"+ body);
System.out.println(body);
String id = body.get("id").toString();
String name = body.get("name").toString();
JSONArray props = new JSONArray(body.get("properties").toString());
An example of a sent object:
{
"id":4,
"name":"test",
"properties":[
{
"house":{
"address":"elm street, 2", ----> this (,) is the responsible part for the error
"postcode":"000012",
"area":"001"
},
"code":"XXX",
"lng":"40.3895",
"created":"2022-04-06:T0:818000200", ---> the (:), also deliver an error
}
]
}
The error I get:
Expected a ':' after a key at character 43
at org.json.JSONTokener.syntaxError(JSONTokener.java:410)
at org.json.JSONObject.<init>(JSONObject.java:203)
at org.json.JSONTokener.nextValue(JSONTokener.java:344)
at org.json.JSONObject.<init>(JSONObject.java:205)
at org.json.JSONTokener.nextValue(JSONTokener.java:344)
at org.json.JSONArray.<init>(JSONArray.java:125)
at org.json.JSONArray.<init>(JSONArray.java:157)
I am integrating the shipment in my application using easy post API when I use shipment.create(shipmentMap, EASYPOSTAPIKEY) it's throwing an error Expected a string but was BEGIN_OBJECT at line 1 column 123 path $.options.
Map<String, Object> parcelMap = new HashMap<String, Object>();
parcelMap.put("predefined_package", "FlatRateEnvelope");
parcelMap.put("weight", 10);
Parcel parcel = Parcel.create(parcelMap);
Map<String, Object> shipmentMap = new HashMap<String, Object>();
shipmentMap.put("to_address", toAddress);
shipmentMap.put("from_address", fromAddress);
shipmentMap.put("parcel", parcel);
Shipment shipment = Shipment.create(shipmentMap, EASYPOSTAPIKEY);
java.lang.IllegalStateException: Expected a string but was
BEGIN_OBJECT at line 1 column 123 path $.options.at
com.google.gson.stream.JsonReader.nextString(JsonReader.java:825)
~[gson-2.8.5.jar:na]
Updating the latest version of easy post client API should fix this.
I am not sure of Easy post API but from exception
options.at com.google.gson.stream.JsonReader.nextString(JsonReader.java:825) ~[gson-2.8.5.jar]
I could say it is related to GSON.
From my understanding GSON says it needs a String but there was an object.
referred this post for that.
GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?
I would ask you to go through the document again and check what you have missed
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");
I am trying to make a call to my REST Service using Object Mapper.
url = new URL("http://phx5qa01c-8539.host.com:8080/bservice/BService/v1/getSimpleString");
String str = mapper.readValue(url, String.class);
And that url will give me this String back-
{ attributes : [ { nm : "SELLERS2" vt : "java.util.Map" status :
"SUCCESS" jsonValue :
"{"lv":[{"v":{"regSiteId":null,"userState":null,"userId":609},"cn":1}],"lmd":20130206211109}"
} ]}
When I am trying that URL on the browser, I am getting back the above String. But as soon as I do the same thing in the code. I am getting this Exception below-
org.codehaus.jackson.map.JsonMappingException: Can not deserialize
instance of java.lang.String out of START_OBJECT token
Can anyone help me with this why I am getting this exception below.
Jackson is trying to deserialize your json as a new string object but the properties dont match up e.g. it cant find a method String.setAttributes(). The 'out of START_OBJECT token' is a catch-all for any deserialisation errors, there may be more info further down the stack trace.
Try:
Map myMap = mapper.readValue(url, Map.class);
Or if you really want the string, don't use Jackson just read the url to a string using standard java code or commons-io:
String str = IOUtils.toString(url);
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);