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.
Related
I have a JSON like this: [{key:key1, value:value1}, {key:key2, value:value2}, ..., {key:keyn, value:valuen}]
and I need a HashMap in Java from that json like: {key1:value1, key2:value2, ..., keyn:valuen}
Is there a simple way to have it converted like this? I'm trying with Jackson but don't know how to specify key and value keywords.
It is very simple:
https://stackoverflow.com/a/24012023/7137584
I would recommend using Jackson library:
import com.fasterxml.jackson.databind.ObjectMapper;
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<>() {};
Map<String, Object> mapping = new ObjectMapper().readValue(jsonStr, typeRef);
The input JSON describes an array/list of map entries where each entry is a POJO:
#Data
class Entry {
private String key;
private String value; // the type of value may be Object
}
Here #Data is a Lombok annotation which provides getters, setters, toString, etc.
So, at first a list of map entries is read, which is converted then to the map:
String json = "[{\"key\":\"key1\", \"value\":\"value1\"}, {\"key\":\"key2\", \"value\":\"value2\"}, {\"key\":\"keyN\", \"value\":\"valueN\"}]";
// step 1: read raw list of entries
List<Entry> input = mapper.readValue(json, new TypeReference<List<Entry>>() {});
// step 2: convert to map
Map<String, String> mapRead = input.stream()
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
System.out.println(mapRead);
Output:
{key1=value1, key2=value2, keyN=valueN}
Here's a solution using the JSON-P api.
import javax.json.*;
var str = "[{\"key\":\"key1\", \"value\":\"value1\"}, {\"key\":\"key2\", \"value\":\"value2\"}, {\"key\":\"keyN\", \"value\":\"valueN\"}]";
JsonReader reader = Json.createReader(new StringReader(str));
JsonArray jarr = reader.readArray();
Map<String,String> map = new HashMap<>();
for(JsonValue jv : jarr) {
JsonObject jo = (JsonObject)jv;
map.put(jo.getString("key"), jo.getString("value") );
}
System.out.println(map);
I am using a JsonReader to convert the String to a JsonArray object.
Each entry of this JsonArray is a JsonObject like {key: keyX, value: valueX}.
I get the values corresponding to 'key' and 'value' and add them to a HashMap using a for loop.
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 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>}
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.