I have json string that should be converted back to a Map type.
Json used:
String jsonString = "{
"varA": "<math><mrow><mn>8</mn></mrow></math>",
"varB": "<math><mrow><mi>m</mi></mrow></math>",
"ans": "<math><mrow><mn>8</mn><mo></mo><mi>m</mi></mrow></math>"
}"
Code that converts json to Map:
Map<String, String> variableMap = gson.fromJson(jsonString, new TypeToken<Map<String,String>>(){}.getType());
Error:
[ERROR] The JsonDeserializer StringTypeAdapter failed to deserialize json object {"varA":"<math><mrow><mn>8</mn></mrow></math>","varB":"<math><mrow><mi>m</mi></mrow></math>","ans":"<math><mrow><mn>8</mn><mo></mo><mi>m</mi></mrow></math>"} given the type class java.lang.String
I know it has something to do with the type, but I have indicated that the type will be String explicitly in the type token.
The gson object is declared as follows:
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
You have to escape the quotes that delimit the JSON string values contained within your Java string. In fact your example is not a valid Java program - Java lacks multi-line strings, for starters.
The following snippet runs just fine (angle brackets and the Unicode character turn out to be innocuous):
public static void main(String[] args) {
String jsonString = "{\"varA\": \"<math><mrow><mn>8</mn></mrow></math>\", \"varB\": \"<math><mrow><mi>m</mi></mrow></math>\", \"ans\": \"<math><mrow><mn>8</mn><mo></mo><mi>m</mi></mrow></math>\"}";
Map<String, String> variableMap = new Gson().fromJson(jsonString, new TypeToken<Map<String,String>>(){}.getType());
System.out.println("foo");
}
It is working when you use Map.class instead of new TypeToken<Map<String,String>>(){}.getType(). See my little example:
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
Map<String, String> map = new HashMap<String, String>();
map.put("varA", "<math><mrow><mn>8</mn></mrow></math>");
map.put("varB", "<math><mrow><mi>m</mi></mrow></math>");
map.put("ans", "<math><mrow><mn>8</mn><mo></mo><mi>m</mi></mrow></math>");
String json = gson.toJson(map);
System.out.println(json);
System.out.println(gson.fromJson(json, Map.class));
It prints:
{
"varB":"<math><mrow><mi>m</mi></mrow></math>",
"ans":"<math><mrow><mn>8</mn><mo></mo><mi>m</mi></mrow></math>",
"varA":"<math><mrow><mn>8</mn></mrow></math>"
}
{varB=<math><mrow><mi>m</mi></mrow></math>, ans=<math><mrow><mn>8</mn><mo></mo><mi>m</mi></mrow></math>, varA=<math><mrow><mn>8</mn></mrow></math>}
Related
I'm very sorry if the title is a little misleading... I really don't know what is exactly the terms but don't worry I have provided my code just in case.
I have a JSON string called json_string, this is its value:
{
"record": {
"sample": "Hello World",
"sample_2": "Hello World_2"
},
"metadata": {
"id": "value",
"private": "true"
}
}
I can convert this JSON string to HashMap using this line of code:
myHashMap = new Gson().fromJson(json_string, new TypeToken<HashMap<String, Object>>(){}.getType());
Now I can get the contents of the key record and pass it to string called final_output using this code:
String final_output = myHashMap.get("record").toString();
the string final_output is:
{ sample=Hello World, sample_2=Hello World_2 }
How can I make it return this format again:
{
"sample": "Hello World",
"sample_2": "Hello World_2"
}
?
Thanks for answering
GSON has a built-in method for pretty printing
.setPrettyPrinting()
To enable Gson pretty print, you must configure the Gson instance using the setPrettyPrinting() method of GsonBuilder class and this method configures Gson to output JSON that fits in a page for pretty printing.
For your case:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
myhashmap = gson.fromJson(json_string, new TypeToken<HashMap<String, Object>>(){}.getType());
Update:
You can get the prettified json Object from a key as a String. (here 'record')
String output = gson.toJson(myHashMap.get("record")).toString();
Maybe this example helps you:
SortedMap<String, String> elements = new TreeMap();
elements.put("Key1", "Value1");
elements.put("Key2", "Value2");
elements.put("Key3", "Value3");
Gson gson = new Gson();
Type gsonType = new TypeToken<HashMap>(){}.getType();
String gsonString = gson.toJson(elements,gsonType);
System.out.println(gsonString);
Output:
{"Key1":"Value1","Key2":"Value2","Key3":"Value3"}
For your case:
Gson gson = new Gson();
Type gsonType = new TypeToken<HashMap>(){}.getType();
String final_output = gson.toJson(myHashMap.get("record"),gsonType);
System.out.println(final_output);
I am using the JSONArray object and I am passing to the constructor of that object a string. The string that I'm passing is
[{\"x\":18.4300,\"y\":30.4700,\"w\":53.0900,\"fontSize\": 11,\"bold\": 0,\"charcount\": 22,\"id\": 349133}].
After out-printing the json object, I get the following:
[{"charcount":22,"w":53.09,"x":18.43,"y":30.47,"fontSize":11,"bold":0,"id":349133}].
Can I get an example in code of how I can preserve the order of the original json string?
You can use a an ordered collection to parse your json to keep it's order.
A sample for your json:
String json = "[{\"x\":18.4300,\"y\":30.4700,\"w\":53.0900,\"fontSize\": 11,\"bold\": 0,\"charcount\": 22,\"id\": 349133}]";
Gson gson = new Gson();
Type type = new TypeToken<Set<LinkedTreeMap<String, Object>>>() {}.getType();
Set<LinkedTreeMap<String, Object>> myMap = gson.fromJson(json, type);
System.out.println(json);
System.out.println(myMap);
I have the following construct in my code for the following JSON
SomeVariable =
{
"FirstVar":{
"service1":"value1"
}
}
For this I have the following
code in Java
Map<String,String> internal_service_var = new HashMap<String,String>();
internal_service_endpoint.put("service1","value1");
Map<String, String> first_var = new HashMap<String,String>();
first_var.put("FirstVar", internal_service_var.entrySet().toString());
Map<String, String> some_var = new HashMap<String, String>();
some_var.put("SomeVariable", first_var.entrySet().toString());
Here is how I try to use it in the JSON to send over wire
Note that the value of the property in the JSON needs to be a String
JSONObject json = new JSONObject
json.put("var", some_var);
This sets the 'var' property in the json to be
[SomeVariable = [ "FirstVar":[ "service1":"value1"]]]
Instead of
SomeVariable = { "FirstVar":{ "service1":"value1"}}
What am I missing?
The toString() of HashMap does not return the data in JSON format. If you want JSON objects use only JSONObject.
Alternatively, use xstream:
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);
String jsonRepresentation = map.toXML();
jsonRepresentation will have your json. Yes, for reasons only known to ancient sages, xstream uses toXML for serialization. It's misnamed, and unlikely to change to anything else.
Here is my code
Gson gson = new Gson();
HashMap<String, String> map = new HashMap<>();
map = gson.fromJson(new FileReader(inputFile), map.getClass());
The content of the inputFile is
{
"key1": "[\"value1\"]",
"key2": "value2"
}
When I inspect the value of map.get("key2") during debugging in Eclipse, the value is actually (java.util.ArrayList<E>) [value1]
How can I make Gson deserialize the content to
{key1="[value1]", key2=value2}
Thanks
I feel like you are seeing the HashMap#toString() output of
{key1=["value1"], key2=value2}
and thinking that
["value1"]
is a List of some type, containing a String value of "value1".
It isn't. Your String, as a String literal, would be represented as "[\"value1\"]". Its value is ["value1"]. That's what gets displayed.
Both your JSON key-value entries are string-string and will get converted as such.
"key1": "[\"value1\"]",
// ^ indicates a JSON string
I'm not very familiar with Java, but got the job to reverse the following JSON-Output to a JAVA object-structure:
Sample:
{"MS":["FRA",56.12,11.67,"BUY"],"DELL":["MUC",54.76,9.07,"SELL"]}
Does someone know, how to build the Arrays / Objetcs and the code to read the strings with Java? JSON or GSON codesamples are welcome.
Thanks!
You could try something like:
Gson gson = new Gson();
Type type = new TypeToken<HashMap<String, String>>(){}.getType();
HashMap<String, String> map = new HashMap<String, String>();
map = gson.fromJson( json, type );
Where "json" is the json string you defined.
Jackson library is most commonly used to parse JSON in Java. Forget about regular expressions and parsing by hand, this is more complicated than you might think. It all boils down to:
String json = "{\"MS\":[\"FRA\",56.12,11.67,\"BUY\"],\"DELL\":[\"MUC\",54.76,9.07,\"SELL\"]}";
ObjectMapper mapper = new ObjectMapper();
Map obj = mapper.readValue(json, Map.class);
You can also map directly to Java beans.