Java Json / Gson put json encoded string to jsonObject without string escapes - java

i first create a Json String with
String myJsonString = new Gson().toJson(myElement);
this works fine.
After that, i want to add this String to anothe big jsonObject to send it to backend with other vars.
jsonObject.put("Tests",myJsonString);
but with this line of code the special character will be escaped and the parser on the backend didnt get it.
How can I avoid it, that myJsonString will be serialized again?
jsonObject.put("Tests",myElement);
doesnt work, because after that there are only references in the jsonObject but no values.

jsonObject.put("Tests", new JSONObject(myJsonString));
(assuming jsonObject is of type org.json.JSONObject)

Related

Error Parsing JSON String to JSONObject in Java

I have an application that stores this JSON String :
String message ="{\"uid\":\"1\",\"streetName\":\"road\",\"city\":\"London\",\"speedLimit\":20}"
Now I want to parse it back to a JSON Object, In order to do so I have this line:
JsonObject object = new JsonParser().parse(message).getAsJsonObject();
I am using Gson Library to parse it and use it as a JSON Object. However, I am getting this exception :
com.google.gson.stream.MalformedJsonException: Expected name at line 1 column 2 path $.
Update 1
I have tried this
String message = "{"uid":"1","streetName":"road","city":"London","speedLimit":20}";
JSONObject object = new JSONObject(message);
Now I get this exception:
Unterminated string at character 28 of {"uid":"1","streetName":"roa
I have tried lots of workarounds from multiple threads on StackOverflow but nothing is working and I have no idea why ?
You can Directly cast it to the JSONObject,
JSONObject response = new JSONObject();
String str = "{\"uid\":\"1\",\"streetName\":\"road\",\"city\":\"London\",\"speedLimit\":20}";
response = new JSONObject(str);
Now the string response has casted as Json response.
you code is fine and should work
please check on the import of the JsonParser in your java file (should be com.google.gson.JsonParser)
let know on the Gson version if the JsonParser is not the issue
your code should work, may be you need to check the dependencies as mentioned before.
I am using this dependency https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.0
here is an sscce that work https://github.com/SalehAly/test-gson
I found my problem.
The String I was processing was malformed for the source. Fixing the string was the answer in here. Nothing was wrong with how I parsed the string.
Thanks for all the answers and the help.

How do I convert a LinkedTreeMap to gson JsonObject

For a java data handler, I send properly formatted JSON, but a combination of Spring, Java deciding how to cast what it sees, and frameworks I really shouldn't go changing mangle that JSON so that once I can see it, it's turned into a LinkedTreeMap, and I need to transform it into a JsonObject.
This is not to serialize/de-serialize JSON into java objects, it's "final form" is a gson JsonObject, and it needs to be able to handle literally any valid JSON.
{
"key":"value",
"object": {
"array":[
"value1",
"please work"
]
}
}
is the sample I've been using, once I see it, it's a LinkedTreeMap that .toString() s to
{key=value, object={array=[value1, please work]}}
where you can replace "=" with ":", but that doesn't have the internal quotes for the
new JsonParser().parse(gson.toJson(STRING)).getAsJsonObject()
strategy.
Is there a more direct way to convert LinkedTreeMap to JsonObject, or a library to add the internal quotes to the string, or even a way to turn a sting into a JsonObject that doesn't need the internal quotes?
You'd typically have to serialize the object to JSON, then parse that JSON back into a JsonObject. Fortunately, Gson provides a toJsonTree method that kind of skips the parsing.
LinkedTreeMap<?,?> yourMap = ...;
JsonObject jsonObject = gson.toJsonTree(yourMap).getAsJsonObject();
Note that, if you can, just deserialize the JSON directly to a JsonObject with
gson.fromJson(theJson, JsonObject.class);

How to put the string in the JSON and get the value in Java

I want to get the value of String and I am trying to put the string in the JSON and get it. The format of string is "key=value&key1=value". The code I am using is:
JSONObject json = new JSONObject(String);
String value = json.get("key").toString();
That string is url encoded not json formatted.
You can use a url decoder instead. Something like http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html might work for you.
I used Patterns and Matchers and it worked perfectly. Thank you.

JSON String to JSON in Java

I have a couple of txt files that gets some information from android's (call,messages,etc) database and stores it as a Cursor object.
I then convert the Cursor onto a JSON object which is then stored on a txt file on an SD card on the device. When I read from the file I get lines as a String like this one:
{"date":1332969098495,"duration":0,"number":"7038673588","Device_ID":"streak"}
I have to store the values of the String onto a MySQL table. Is there a way that I can convert this back onto a JSON or maybe a Map?
I thought about editing the String so the values are surrounded by a single quote and use the MySQL syntax to simply load the fields on the file.
Thanks!
You can create a JSONObject from the string that you have. That will pretty much give the same functionality as that of java.util.Map. For e.g,
String jsonStr = "json representation of your data";
JSONObject jObj = new JSONObject(jsonStr);
jObj.get(yourKeyString);
//do more with your jObj here...
Hope this helps. Refer the JSONObject documentation for more details.
You need to use JSon-lib (or) GSon libraries for this purpose.
Example GSon code would be:
YourObject obj = gson.fromJson(inputJson, YourObject.class);
Note: YourObject is java class with getter/setter.
Here is an tutorial of using GSON library to achieve typed object conversion.
http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/
Sathishpaul is correct but just to clarify :
JSONObject obj = new JSONObject(YourJSONString);
Long date = obj.getLong("date");
int duration = obj.getInt("duration");
etc..

org.json.JSONObject constructor not accepting what appears to be a valid JSON string

I have a string in an Android app that I am trying to convert into a JSONObject. The string looks like this (except longer and with actual values instead of the dummy values I entered here):
[[{"1":"a"}],[{"1a":"1a","1b":"1b"},{"2a":"2a","2b":"2b"}]]
I have entered this exact string into two online JSON validators, and both of them confirm it to be valid JSON data. So I would assume that the JSONObject constructor would be able to accept this string and convert it into a JSONObject. But when I try:
json = new JSONObject(result);
Where "result" is a String variable containing the string listed above, I get the following exception:
JSONException: A JSONObject text must begin with '{' at character 1 of [[{"1":"a"}],[{"1a":"1a","1b":"1b"},{"2a":"2a","2b":"2b"}]]
What's going on here? Is the JSONObject's parser broken?
You are trying to create a JSONObject, but what you are actually giving it is a JSONArray. Did you try creating a JSONArray instead?
Alternatively, you could wrap your array in an object so that you can create a JSONObject out of it.
I would suggest using the GSon library instead as it appears to be more full-featured.
In addition, it may be helpful to use this tool to test your data (your data is valid btw):

Categories

Resources