Deserialize json with duplicate keys using Jackson - java

I am trying to parse a json payload with duplicate keys to a Map<String, List<String>> using Jackson
Consider the following payload
{
"foo" : "val1",
"foo" : "val2",
"bar" : "val3"
}
I want to convert this to a Map<String, List<String>> type.
ex:
+--------------+----------------------+
| Key (String) | Value (List<String>) |
+--------------+----------------------+
| foo | [val1, val2] |
| bar | [val3] |
+--------------+----------------------+
What would be the best way to handle this with Jackson? I'm hoping that there's a way in Jackson where I can register a custom deserialization logic for Map<String, List<String>> type. (Note that I have no control over the json payload sent in the request)
Appreciate any help on this.
Thanks!

Check if it works for you.
Using #JsonAnySetter to deserialize unmapped JSON properties. #JsonAnySetter annotation can be used to define "any setter" mutator.
Using #JsonAnyGetter Annotation to serialize any arbitrary properties. #JsonAnyGetter can be used on a method which returns a Map.
POJO Definition
Test.java
package oct2020.json;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
public class Test {
private Map<String, List<String>> keyValuesMap = new HashMap<String, List<String>>();
/**
* #return the keyValuesMap
*/
#JsonAnyGetter
public Map<String, List<String>> getKeyValuesMap() {
return keyValuesMap;
}
/**
* #param keyValuesMap
* the keyValuesMap to set
*/
public void setKeyValuesMap(Map<String, List<String>> keyValuesMap) {
this.keyValuesMap = keyValuesMap;
}
#JsonAnySetter
public void duplicateKeyValues(String key, String value) {
List<String> values = null;
if (!keyValuesMap.containsKey(key)) {
values = new ArrayList<String>();
} else {
values = keyValuesMap.get(key);
}
values.add(value);
keyValuesMap.put(key, values);
}
}
Converting the json to desired format.
JSONConverter .java
package oct2020.json;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JSONConverter {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = "{\n\"foo\" : \"val1\",\n\"foo\" : \"val2\",\n\"bar\" : \"val3\"\n,"
+ "\n\"bar\" : \"val3\"\n,\n\"bar\" : \"val3\"\n,\n\"bar\" : \"val3\"\n,"
+ "\n\"bar\" : \"val3\"\n,\n\"bar\" : \"val3\"\n,\n\"bar\" : \"val3\"\n,"
+ "\n\"bar\" : \"val3\"\n,\n\"bar\" : \"val3\"\n,\n\"bar\" : \"val3\"}";
Test test = mapper.readValue(json, Test.class);
Map<String, List<String>> keyValuesMap = test.getKeyValuesMap();
System.out.println(mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(keyValuesMap));
}
}
Output:
{
"bar" : [ "val3", "val3", "val3", "val3", "val3", "val3", "val3", "val3", "val3", "val3" ],
"foo" : [ "val1", "val2" ]
}

please put this property JsonTypeInfo.As.EXISTING_PROPERTY in the #JsonTypeInfo annotation. It might work.

Related

How to create Array of Objects using the Jackson Streaming API

I am trying to create a JSON using the Jackson Streaming API. I know how to create an array of elements in JSON using Jackson as we have plenty of examples related to it. But I am a bit confused about how to create an array of Objects using it.
Following is the JSON structure that I would like to obtain at the end:
{
"name" : "Batman",
"year" : 2008,
"writers":[
{
"name" : "Nolan",
"age" : 49
},
{
"name" : "Johnathan",
"age" : 35
}
]
}
Following is the code I have:
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
public class HelloWorld {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
ByteArrayOutputStream jsonStream = new ByteArrayOutputStream();
JsonGenerator jsonGenerator = mapper.getFactory().createGenerator(jsonStream, JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "Batman");
jsonGenerator.writeNumberField("year", 2008);
jsonGenerator.writeFieldName("writers");
jsonGenerator.writeStartArray();
// How to to create here objects and add it to the "writers"
// Should I create another JsonGenerator and create objects usign it?
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
String jsonData = new String(jsonStream.toByteArray(), "UTF-8");
JSONObject json = new JSONObject(jsonData);
System.out.println(json.toString(4));
}
}
Can someone please guide me on how to create the objects and add them to the array one by one? I am unable to find such an example so posting here.
I would just create a Map to store the data. For the writers, you can call List.of to create an in-line List.
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.databind.*;
public class MovieDataWriter {
public static void main(String[] args) {
Map<String, Object> movieData = createMap(
"name", "Batman",
"year", 2008,
"writers", List.of(
createMap(
"name", "Nolan",
"age", 49
),
createMap(
"name", "Johnathan",
"age", 35
)
)
);
writeToFile(movieData, "target/batman.json");
}
private static void writeToFile(Map<String, Object> data, String filename) {
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
try {
writer.writeValue(new File(filename), data);
} catch (IOException e) {
e.printStackTrace();
}
}
private static Map<String, Object> createMap(Object ...args) {
Map<String, Object> pairs = new LinkedHashMap<>();
for (int i = 0; i < args.length; i += 2) {
pairs.put(String.valueOf(args[i]), args[i + 1]);
}
return pairs;
}
}
Dependencies
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.1</version>
</dependency>
batman.json
{
"name" : "Batman",
"year" : 2008,
"writers" : [ {
"name" : "Nolan",
"age" : 49
}, {
"name" : "Johnathan",
"age" : 35
} ]
}
After trying a few things I was able to get it. Basically, I had to do the same thing which I was asked in the question. I am not sure why it did not work the first time maybe I missed something. Anyways here is how you can add objects into the array using the Jackson Streaming API. Posting this as it can be beneficial to someone else in the future.
I am creating an array writers in this case and adding the objects into it using the same jsonGenerator.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
public class HelloWorld {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
ByteArrayOutputStream jsonStream = new ByteArrayOutputStream();
JsonGenerator jsonGenerator = mapper.getFactory().createGenerator(jsonStream, JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "Batman");
jsonGenerator.writeNumberField("year", 2008);
jsonGenerator.writeFieldName("writers");
jsonGenerator.writeStartArray();
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "Nolan");
jsonGenerator.writeNumberField("age", 45);
jsonGenerator.writeEndObject();
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "Johanathan");
jsonGenerator.writeNumberField("age", 35);
jsonGenerator.writeEndObject();
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
String jsonData = new String(jsonStream.toByteArray(), "UTF-8");
JSONObject json = new JSONObject(jsonData);
System.out.println(json.toString(4));
}
}
You will get the output something like this:
{
"year": 2008,
"name": "Batman",
"writers": [
{
"name": "Nolan",
"age": 45
},
{
"name": "Johanathan",
"age": 35
}
]
}

how to read a csv to a nested json with jackson java

i have this type of csv :
metric,value,date
temp_a,622.0,1477895624866
temp_a,-3.0,1477916224866
temp_a,365.0,1477917224866
temp_b,861.0,1477895624866
temp_b,767.0,1477917224866
and i want to use java jackson to convert it to json but not any json; it needs to be like this:
[
{
"metric":"temp_a",
"datapoints":[
[622, 1477895624866],
[-3, 1477916224866],
[365, 1477917224866]
]
},
{
"metric":"temp_b",
"datapoints":[
[861, 1477895624866],
[767, 1477917224866]
]
}
]
where dataponits is an array containing the value and the date in the csv .
i have managed to use the jackson to get this result :
{metric=temp_a, value=622.0, date=1477895624866}
{metric=temp_a, value=-3.0, date=1477916224866}
{metric=temp_a, value=365.0, date=1477917224866}
{metric=temp_b, value=861.0, date=1477895624866}
{metric=temp_b, value=767.0, date=1477917224866}
but it is not what i want and the jackson doc is a bit hard for me to understand and play with , may be this is possible with Pojos or annotations but i can't understand them, i couldn't find how to do a nested json.
if i can do this better this something else then jackson please tell me .
thank you for helping.
You do not have to always deserialise CSV to a POJO structure and implement custom serialisers. In this case, you can also:
Deserialise CSV to a Map
Group by elements in a Map to a form metric -> [[...], [...]]
Convert above Map to another form of Map
Serialise Map to a JSON
Example code could look like below:
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import java.io.File;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class CsvApp {
public static void main(String[] args) throws Exception {
File csvFile = new File("./resource/test.csv").getAbsoluteFile();
CsvMapper csvMapper = CsvMapper.builder().build();
MappingIterator<Map> rows = csvMapper
.readerWithSchemaFor(Map.class)
.with(CsvSchema.emptySchema().withHeader())
.readValues(csvFile);
DataConverter converter = new DataConverter();
List<Map<String, Object>> result = converter.toMetricDataPoints(rows);
ObjectMapper jsonMapper = JsonMapper.builder()
.enable(SerializationFeature.INDENT_OUTPUT)
.build();
jsonMapper.writeValue(System.out, result);
}
}
class DataConverter {
public List<Map<String, Object>> toMetricDataPoints(MappingIterator<Map> rows) {
return toStream(rows)
//group by metric -> [value, date]
.collect(Collectors.groupingBy(map -> map.get("metric"),
Collectors.mapping(map -> Arrays.asList(toNumber(map.get("value")), toNumber(map.get("date"))),
Collectors.toList())))
.entrySet().stream()
// convert to Map: metric + datapoints
.map(entry -> {
Map<String, Object> res = new LinkedHashMap<>(4);
res.put("metric", entry.getKey());
res.put("datapoints", entry.getValue());
return res;
}).collect(Collectors.toList());
}
private Stream<Map> toStream(MappingIterator<Map> rowIterator) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(rowIterator, Spliterator.ORDERED), false);
}
private long toNumber(Object value) {
return new BigDecimal(Objects.toString(value, "0")).longValue();
}
}
Above code prints:
[ {
"metric" : "temp_a",
"datapoints" : [ [ 622, 1477895624866 ], [ -3, 1477916224866 ], [ 365, 1477917224866 ] ]
}, {
"metric" : "temp_b",
"datapoints" : [ [ 861, 1477895624866 ], [ 767, 1477917224866 ] ]
} ]
As you can see, we used only basic Jackson functionality, rest of manipulation on data we implemented using Java 8 API.
See also:
Directly convert CSV file to JSON file using the Jackson library
How to convert an iterator to a stream?
Jackson JSON Deserialization: array elements in each line

Parsing the openweatherMap json file

I am working on a project,which requires to get weather information and so i used openweathermap api. My program worked and i got information from "main" and "wind" ,but i also need to get description from the main weather set.The problem is that the weather set is a list in the json file and i am unable to cast it to map.The example json file which i am trying to parse is http://api.openweathermap.org/data/2.5/weather?q=London
JSON:
{
"coord":{
"lon":-0.13,
"lat":51.51
},
"weather":[
{
"id":803,
"main":"Clouds",
"description":"broken clouds",
"icon":"04n"
}
],
"base":"stations",
"main":{
"temp":43.56,
"pressure":1004,
"humidity":87,
"temp_min":41,
"temp_max":46.4
},
"visibility":10000,
"wind":{
"speed":11.41,
"deg":80
},
"rain":{
},
"clouds":{
"all":75
},
"dt":1573350303,
"sys":{
"type":1,
"id":1414,
"country":"GB",
"sunrise":1573369754,
"sunset":1573402780
},
"timezone":0,
"id":2643743,
"name":"London",
"cod":200
}
When we look at the file,we notice that there is an [] bracket inside the weather set which is creating problems in my project.I tried to look up on how to cast list to map and tried playing with my code ,but didn't help.The commented code in the file are things which i have tried while trying to make it work.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.*;
import com.google.gson.reflect.*;
import java.util.List;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class PlantWateringApp {
public static Map<String, Object> jsonToMap(String str) {
Map<String, Object> map = new Gson().fromJson(str, new TypeToken<HashMap<String, Object>>() {
}.getType());
return map;
}
public static void main(String[] args) {
String LOCATION = "delhi,india";
String result = "{\"coord\":{\"lon\":77.22,\"lat\":28.65},\"weather\":[{\"id\":711,\"main\":\"Smoke\",\"description\":\"smoke\",\"icon\":\"50d\"}],\"base\":\"stations\",\"main\":{\"temp\":72.32,\"pressure\":1015,\"humidity\":59,\"temp_min\":64.4,\"temp_max\":77},\"visibility\":1000,\"wind\":{\"speed\":3.36,\"deg\":270},\"clouds\":{\"all\":0},\"dt\":1573351180,\"sys\":{\"type\":1,\"id\":9165,\"country\":\"IN\",\"sunrise\":1573348168,\"sunset\":1573387234},\"timezone\":19800,\"id\":1273294,\"name\":\"Delhi\",\"cod\":200}";
System.out.println(result);
Map<String, Object> respMap = jsonToMap(result.toString());
Map<String, Object> mainMap = jsonToMap(respMap.get("main").toString());
Map<String, Object> windMap = jsonToMap(respMap.get("wind").toString());
// Type listType = new TypeToken<List<Map<String,String>>>()
// {}.getType();
// List<Map<String,String>> weatherMap = new
// Gson().fromJson(respMap.get("description").toString(),listType);
// Map<String, Object> name = (Map<String, Object>)
// respMap.get("description");
// Map<String, Object > weatherMap = jsonToMap
// (respMap.get("description").toString());
System.out.println("Location: " + LOCATION);
System.out.println("Current Temperature: " + mainMap.get("temp"));
System.out.println("Current Humidity: " + mainMap.get("humidity"));
System.out.println("Max: " + mainMap.get("temp_min"));
System.out.println("Min: " + mainMap.get("temp_max"));
System.out.println("Wind Speed: " + windMap.get("speed"));
System.out.println("Wind Angle: " + windMap.get("deg"));
}
}
I tried to do the same way as i did for main and wind : Map weatherMap = jsonToMap (respMap.get("weather").toString()); .But i got errors:
////java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 3 path $[0]
So i tried to not convert json to Map rather directly use map like Map weatherMap = (Map) respMap.get("weather"); but i got
////java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Map
For this,i tried to cast list to map using
List<Map<String,String>> weatherMap = new Gson().fromJson(respMap.get("weather").toString(),listType);
But this says:
//String cannot be converted to int
I am really confused on what to do in this situation.I am unable to figure out how to deal with [] in the json file.
As this data is provided as a List and you are trying to convert it into the Map. That is not right. You need to get it (weather) as a list of Map and then need to treat each element as Map. Here is an example how to get it as a Map
///...
//// other code
///...
Map<String, Object > respMap = jsonToMap (result.toString());
// don't need to convert from string to map again and again
Map<String, Object > mainMap = (Map<String, Object >)respMap.get("main");
Map<String, Object > windMap = (Map<String, Object >)respMap.get("wind");
// fist get weather as list
List<Map<String, Object >> weather = (List<Map<String, Object>>) (respMap.get("weather"));
//...
System.out.println("Wind Speed: " + windMap.get("speed") );
System.out.println("Wind Angle: " + windMap.get("deg") );
// weather as list
System.out.println("Weather: "+ weather);
// assuming weather contains at-least 1 element.
Map<String, Object> weatherMap = weather.get(0);
System.out.println("Weather as map: "+ weatherMap);
Casting it to list.
List<Map<String, Object >> weather = (List<Map<String, Object>>) (respMap.get("weather"));
Then treat each element as Map:
// assuming weather contains at-least 1 element.
Map<String, Object> weatherMap = weather.get(0);
Hope this helps.
Make life simple and use real types.
import java.util.List;
import com.google.gson.Gson;
public class PlantWateringApp {
class Weather_2_5 {
List<Weather> weather;
}
class Weather {
Integer id;
String main;
String description;
String icon;
}
public static void main(String[] args) {
String result = "{\"coord\":{\"lon\":77.22,\"lat\":28.65},\"weather\":[{\"id\":711,\"main\":\"Smoke\",\"description\":\"smoke\",\"icon\":\"50d\"}],\"base\":\"stations\",\"main\":{\"temp\":72.32,\"pressure\":1015,\"humidity\":59,\"temp_min\":64.4,\"temp_max\":77},\"visibility\":1000,\"wind\":{\"speed\":3.36,\"deg\":270},\"clouds\":{\"all\":0},\"dt\":1573351180,\"sys\":{\"type\":1,\"id\":9165,\"country\":\"IN\",\"sunrise\":1573348168,\"sunset\":1573387234},\"timezone\":19800,\"id\":1273294,\"name\":\"Delhi\",\"cod\":200}";
//System.out.println(result);
Gson G = new Gson();
Weather_2_5 obj = G.fromJson(result, Weather_2_5.class);
for (int idx = 0; idx < obj.weather.size(); idx++) {
System.out.println(obj.weather.get(idx).description);
}
}
}
Instead of writing it all from the beginning you could use:
https://github.com/xSAVIKx/openweathermap-java-api
I think this example is closest to what you are trying to do:
https://github.com/xSAVIKx/openweathermap-java-api/blob/development/api-examples/src/main/java/org/openweathermap/api/example/CurrentWeatherOneLocationExample.java

Convert JSON record to LinkedHashMap<String,String> using Jackson API

I have a JSON file(it contains an array of JSON objects.)
I am trying to read it object by object.
Each object I need to convert it to a LinkedHashMap<String,String> where both the key and value are strings. Note that even if the JSON objects contain a non-string value(Integer/Boolean), I want my LinkedHashMap to contain a string.
This is my JSON file (films.json):
[
{
"name": "Fight Club",
"year": 1999,
}
]
Now, this has 1 object. I want to convert it to a LinkedHashMap<String,String>.
So for the above example, my LinkedHashMap should contain(for the 1st JSON object) :
"name" : "Fight CLub"
"year" : "1999"
Notice how the year is String in the LinkedHashMap and not Integer.
This is what I tried.
Map<String, Object> myLinkedHashMap;
JsonParser jsonParser = new JsonFactory().createParser(new File("films.json"));
jsonParser = new JsonFactory().createParser(new File(filePath));
jsonParser.nextToken();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
while(jsonParser.nextToken() != JsonToken.END_ARRAY){
myLinkedHashMap = mapper.readValue(jsonParser, LinkedHashMap.class);
}
The variable myLinkedHashMap will contain a key/value pair for an object in my JSON file.
But the problem is that for 'year' of the JSON file, I am getting Integer in the LinkedHashMap as the JSON file also contains Integer.
Instead, I want the Integer as String in the LinkedHashMap.
Please help me get String in the LinkedHashMap instead of Integer.
Note: The solution should be generic to other data types also.
So if the JSON object contains boolean true, then my LinkedHashMap should contain "true".
You can construct map type using TypeFactory and constructMapType method to tell exactly what do you need from readValue method. See below example:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.util.Assert;
import java.io.File;
import java.util.LinkedHashMap;
public class JsonMapApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
JsonParser jsonParser = mapper.getFactory().createParser(jsonFile);
jsonParser.nextToken();
MapType mapType = mapper.getTypeFactory().constructMapType(LinkedHashMap.class, String.class, String.class);
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
LinkedHashMap<String, String> map = mapper.readValue(jsonParser, mapType);
map.forEach((k, v) -> {
Assert.isInstanceOf(String.class, v);
System.out.println(k + " -> " + v + " (" + v.getClass().getName() + ")");
});
}
}
}
Above code prints:
name -> Fight Club (java.lang.String)
year -> 1999 (java.lang.String)
Change
Map<String, Object> myLinkedHashMap;
to
Map<String, String> myLinkedHashMap;

Escape String backslash using GSON

I am trying to convert my hashmap to a JSON pretty print output.
I tried GSON and believe there is some issue with it handling string as inputs inside a map, is there any other way to do this?
Map<String, String> map = new LinkedHashMap();
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().setPrettyPrinting().create();
map.put("Intro", Map_to_String);
map.put("Output", String_Val);
System.out.println(gson.toJson(map));
Output:
{
"Intro": {\"No\":0,\"Cast\":2},
"Output": "123"
}
Required Output:
{
"Intro": {"No":0,"Cast":2},
"Output": "123"
}
You need to deserialise Map_to_String back to object - Map in this case and after that serialise again.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.Map;
public class GsonApp {
public static void main(String[] args) {
Map<String, Object> map = new LinkedHashMap<>();
Gson gson = new GsonBuilder()
.enableComplexMapKeySerialization()
.setPrettyPrinting()
.create();
String jsonString = "{\"No\":0,\"Cast\":2}";
Type mapType = new TypeToken<Map<String, String>>() {}.getType();
map.put("Intro", gson.fromJson(jsonString, mapType));
map.put("Output", "123");
System.out.println(gson.toJson(map));
}
}
Prints:
{
"Intro": {
"No": "0",
"Cast": "2"
},
"Output": "123"
}

Categories