I've got a JSON structure like the following:
{
"identifier": 1045608,
"scientificName": "Apis mellifera Linnaeus 1758",
"exemplar": false,
"richness_score": 400.0,
"dataObjects": [
{
"identifier": "d72801627bf4adf1a38d9c5f10cc767f",
"dataObjectVersionID": 30073527,
"dataType": "http://purl.org/dc/dcmitype/StillImage",
"dataSubtype": "",
"vettedStatus": "Trusted",
"dataRatings": {
"1": 0,
"2": 0,
"3": 4,
"4": 0,
"5": 6
},
"dataRating": 4.2,
"mimeType": "image/jpeg",
"created": "2009-07-12T15:13:19Z",
"title": "Honey Bee on Mountain Mint",
"language": "en",
"license": "http://creativecommons.org/licenses/by/2.0/",
"rightsHolder": "John Baker",
"source": "https://www.flickr.com/photos/38875278#N08/3730360050/",
"mediaURL": "https://farm3.staticflickr.com/2619/3730360050_c771a4c2cf_o.jpg",
"agents": [
{
"full_name": "John Baker",
"homepage": "http://www.flickr.com/photos/38875278#N08",
"role": "photographer"
},
{
"full_name": "Flickr: EOL Images",
"homepage": "http://www.flickr.com/groups/encyclopedia_of_life",
"role": "provider"
}
],
}
]
}
I have defined a top-level class to deserialize into as:
class EOLDataObjectsResponse {
private int identifier;
private String scientificName;
private Boolean exemplar;
#SerializedName("richness_score") private float richnessScore;
private List<EOLDataObjectsTaxonConcept> taxonConcepts;
private List<LinkedTreeMap<String, String>> dataObjects;
}
Everything was parsing properly with Gson until I added the dataObjects property. What I am getting on testing is:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2242 path $.dataObjects[0].
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
at com.google.gson.Gson.fromJson(Gson.java:887)
at com.google.gson.Gson.fromJson(Gson.java:825)
at emt.eol.EOLDataObjects.query(EOLDataObjects.java:102)
at emt.eol.EOLDataObjects.query(EOLDataObjects.java:51)
at emt.eol.EOLDataObjects.main(EOLDataObjects.java:136)
What I would like to do is parse just that property into a list of nested maps of string-string pairs since I have no guarantees re what is coming back in that list yet want to make it available in a nested map format if someone needs to access it. I was hoping that the Gson LinkedTreeMap class would do the trick, but apparently not the way I'm using it.
Can anyone suggest what might be causing problems or possibly a better approach? Thanks!
dataObjects is not a key as other strings. It is a json object. You have to parse it as JSON Object separately.
public static Map parse(final String json,final Map map){
try {
//Instance of JsonFactory for Object Mapper istance
final JsonFactory factory = new JsonFactory();
final ObjectMapper mapper = new ObjectMapper(factory);
//create JsonNode from json String
final JsonNode rootNode = mapper.readTree(json);
// iterate till it fetch all parameter and value from json string
final Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
while (fieldsIterator.hasNext()) {
final Map.Entry<String, JsonNode> field = fieldsIterator.next();
//if normal json, put value to map
map.put(field.getKey(), String.valueOf(field.getValue()));
//if json oject again recurse parse method.
if ((String.valueOf(field.getValue()).startsWith("{") && String.valueOf(field.getValue()).endsWith("}"))) {
parse(String.valueOf(field.getValue()),map);
}
//if json array it invoke parseJsonArray
if (String.valueOf(field.getValue()).startsWith("[{") && String.valueOf(field.getValue()).endsWith("}]")) {
parseJsonArray(String.valueOf(field.getValue()),map);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public static void parseJsonArray(String jsonArray,Map<String, String> map) {
try {
JSONArray jsonArray1 = new JSONArray(jsonArray);
for (int i = 0; i < jsonArray1.length(); i++) {
JSONObject json = jsonArray1.getJSONObject(i);
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
map.put(key, String.valueOf(json.get(key)));
System.out.println("Key :" + key + " Value :" + String.valueOf(json.get(key)));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Related
My API needs to return a list of entry objects from the JSON below. I am using jersey and jackson. I would ideally like to only create a java class PermissionEnty , and my API to return a list of PermissionEntry objects from the JSON. I am not able to deserialize using the below approach? Can someone advise what could be the issue? I have added UNWRAP_ROOT_VALUE so I presume the 'list' node it ignored, and I would get items below 'list' node.
public class PermissionEntry {
private String id;
private String displayName;
private String memberType;
}
and the json;
{
"list": {
"pagination": {
"count": 5,
"hasMoreItems": false,
},
"entries": [
{
"entry": {
"displayName": "norma",
"id": "norma",
"memberType": "PERSON"
}
},
{
"entry": {
"displayName": "clara",
"id": "clara",
"memberType": "PERSON"
}
},
{
"entry": {
"displayName": "michael",
"id": "mich",
"memberType": "PERSON"
}
}
]
}
}
PermissionEntries
public class PermissionEntries {
#JsonProperty(value = "entries")
#JsonDeserialize(using = PermissionEntryDeserializer.class)
private List<PermissionEntry> entries;
public List<PermissionEntry> getEntries() {
return entries;
}
public void setEntries(List<PermissionEntry> entries) {
this.entries = entries;
}
}
Below is the deserializer that I am using
public class PermissionEntryDeserializer extends JsonDeserializer<List<PermissionEntry>> {
private static final String ENTRY = "entries";
private static final ObjectMapper mapper = new ObjectMapper()
.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
private static final CollectionType collectionType =
TypeFactory
.defaultInstance()
.constructCollectionType(List.class, PermissionEntry.class);
#Override
public List<PermissionEntry> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
ObjectNode objectNode = mapper.readTree(jsonParser);
JsonNode nodeEntries = objectNode.get(ENTRY);
if (null == nodeEntries // if no ENTRY node could be found
|| !nodeEntries.isArray() // or ENTRY node is not an array
|| !nodeEntries.elements().hasNext()) // or ENTRY node doesn't contain any entry
return null;
return mapper.readerFor(collectionType).readValue(nodeEntries);
}
}
Service API
public Optional<List<PermissionEntry>> getPermissionsForGroup(String groupName) {
Response response = getTarget()
.path("/api/group/" + groupName + "/members")
.request()
.get();
PermissionEntries list = response.readEntity(PermissionEntries.class);
}
I don't understand what you mean in this question 'Can someone please tell me how many java classes do I need to create to get a list of entries.' but you had already an entry object called PermissionEntry. You will have the list of this object.
This is the jersey client of your data with jakcson .
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
String URL = "http://{{host}}:{{port}}/entry";
WebResource webResourceGet = client.resource(URL);
ClientResponse response = webResourceGet.accept("application/json").get(ClientResponse.class);
String output = response.getEntity(String.class);
ResponseList responseList= mapper.readValue(output , ResponseList .class);//here is the permissionEntry list that you wil have
Also, you should create an object given name as Pagination for pagination that is in the json data. You can make an another object that includes List<PermissionEntry> and Pagination called ResponseList.
I have a Json like below:
{
"searchResults": {
"searchCriteria": {
"location": {
"originalLocation": null
},
"startAndEndDate": {
"start": "2016-10-06T00:00:00",
"end": "2016-10-09T00:00:00"
},
"solution": [
{
"resultID": "O1MDc1MD",
"selected": false,
"charges": {
"localCurrencyCode": "USD",
"averagePricePerNight": 153
},
"starRating": 3.5
},
{
"resultID": "0MDc1MD",
"selected": false,
"charges": {
"localCurrencyCode": "USD",
"averagePricePerNight": 153
},
"starRating": 3.5
}
....
I have class with attributes starRating and averagePricePerNight which essentially formulates into my POJO.
class ResponseModel {
Int starRating; Int averagePricePerNight
}
I want to parse this JSON and return a List containing :
List(ResponseModel(3.5,900), ResponseModel(3.5,100), ResponseModel(4.5,1000))
I tried to get the json as a List but then i am unable to find examples to get two elements from JSon.
You can write a custom deserializer:
class Deserializers {
public static ResponseModel responseModelDeserializer(JsonElement json, Type typeOfT,
JsonDeserializationContext context) {
JsonObject obj1 = json.getAsJsonObject();
JsonObject obj2 = obj1.get("charges").getAsJsonObject();
double starRating = obj1.get("starRating").getAsDouble();
int averagePricePerNight = obj2.get("averagePricePerNight").getAsInt();
return new ResponseModel(starRating, averagePricePerNight);
}
}
Register it when building Gson:
Gson gson = new GsonBuilder()
.registerTypeAdapter(ResponseModel.class,
(JsonDeserializer<ResponseModel>) Deserializers::responseModelDeserializer
// ^^^ Cast is needed because the parameter has type Object
)
.create();
(Other options include, besides a method reference, are; lambda, anonymous class, or just a regular class. But this one is my favourite.)
Parse your json:
// Get root json object
JsonObject root = new JsonParser().parse(input).getAsJsonObject();
Type tt = new TypeToken<List<ResponseModel>>() {}.getType();
// Get array
List<ResponseModel> mo = gson.fromJson(root.get("solution"), tt);
System.out.println(mo); // [3.5 : 153, 3.5 : 153]
Where ResponseModel is:
class ResponseModel {
private final double starRating;
private final int averagePricePerNight;
public ResponseModel(double starRating, int averagePricePerNight) {
this.starRating = starRating;
this.averagePricePerNight = averagePricePerNight;
}
#Override
public String toString() {
return String.format("%s : %s", starRating, averagePricePerNight);
}
}
I made starRating a double since it seems to be one in your example.
I have written a program that does some probability calculations and gives its results in the form of arrays. I want to convert these results to JSON format, but I am having issues.
I want my json object to look like this:
{
"totalSuggestions": 6,
"routes": {
"rank_2": {
"Source": "ABC",
"Weight": "0.719010390625",
"Destination": "XYZ"
},
"rank_1": {
"Source": "XYZ",
"Weight": "0.7411458281249999",
"Destination": "ABC"
},
"rank_0": {
"Source": "LMN",
"Weight": "0.994583325",
"Destination": "PQR"
}
}
}
What I understood is that I need to have an object class with the structure of my objects. For now I am experimenting with the rank object only but failing to form the required JSON.
My code for the object structure:
public class Object {
int rank_;
public class Inner{
String Source;
String Destination;
String Weightage;
}
}
I can pass either an instance of Object or an instance of Inner to toJson() method so I either get {"rank_":1} or {"Source":"ABC","Destination":"XYZ","Weightage":"123"}.
I cant seem to put each of the inner object to the corresponding rank object.
I did it with relative ease with org.json but that library has some issues with Android studio so I had to switch to Gson. What I did earlier (which worked as well) was:
public JSONObject convertToJson(int mkr, String[][] result){
JSONObject outerObj = new JSONObject();
JSONObject innerObj = new JSONObject();
JSONObject[] temp = new JSONObject[mkr];
outerObj.put("totalSuggestions", marker);
outerObj.put("routes",innerObj);
for (int i=0;i<marker;i++){
String[] useless = result[i][0].split("-");
temp[i]= new JSONObject();
temp[i].put("Source",useless[0] );
temp[i].put("Destination", useless[1]);
temp[i].put("Weight", result[i][1]);
innerObj.put("rank_"+i, temp[i]);
}
System.out.println(outerObj.toString());
return outerObj;
}
Well, first: related objects should probably be in a class together. So lets start with a simple class:
public class Results {
int mkr;
String[][] result;
}
Now we want to serialize it. We could construct a different data structure, or we could just write our own custom serializer. We want to have our custom class to allow us to use Gson's type inference for doing so, plus the code is just easier to understand. I will show you how to serialize the data structure, and I'll leave the deserialization as an exercise for you.
We create a TypeAdapter<Results>:
public class ResultsAdapter extends TypeAdapter<Results> {
public Results read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
// exercise for you
return results;
}
public void write(JsonWriter writer, Results value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
writer.beginObject();
writer.name("totalSuggestions").value(value.mkr);
writer.name("routes");
writer.beginObject();
for(int i = 0; i < value.mkr; i++) {
writer.name("rank_"+i);
writer.beginObject();
String[] sourceDestSplit = result[i][0].split("-");
writer.name("Source").value(sourceDestSplit[0]);
writer.name("Destination").value(sourceDestSplit[1]);
writer.name("Weight").value(result[i][1]);
writer.endObject();
}
writer.endObject();
writer.endObject();
}
}
You can then call this method by doing (note: should only create the Gson object once, but I did it this way to keep the code short):
public String convertToJson(Results results) {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(new ResultsAdapter()):
Gson gson = builder.build();
return gson.toJson(results);
}
This will work you the way you've asked, but I strongly recommend using JSON's array syntax instead (using []). Try this instead:
public void write(JsonWriter writer, Results value) throws IOException {
if (value == null) {
writer.nullValue();
return;
}
writer.beginObject();
writer.name("totalSuggestions").value(value.mkr);
writer.name("routes");
writer.beginArray();
for(int i = 0; i < value.mkr; i++) {
writer.beginObject();
String[] sourceDestSplit = result[i][0].split("-");
writer.name("Source").value(sourceDestSplit[0]);
writer.name("Destination").value(sourceDestSplit[1]);
writer.name("Weight").value(result[i][1]);
writer.endObject();
}
writer.endArray();
writer.endObject();
}
Doing it this will will result in JSON that looks like this, which will be easier to deserialize on the other side and iterate through, because you won't have to dynamically generate maps for the keys.:
{
"totalSuggestions": 6,
"routes": [
{
"Source": "ABC",
"Weight": "0.719010390625",
"Destination": "XYZ"
},
{
"Source": "XYZ",
"Weight": "0.7411458281249999",
"Destination": "ABC"
},
{
"Source": "LMN",
"Weight": "0.994583325",
"Destination": "PQR"
}
]
}
I landed here while searching for a similar solution for the com.google.gson.JsonObject library. Now, I've found it:
JsonObject mainJson = new JsonObject();
JsonObject innerJson = new JsonObject();
innerJson.addProperty("#iot.id", "31");
mainJson.add("Datastream", innerJson); // <-- here the nesting happens
mainJson.addProperty("result", 12.3);
// fetch inner variable like this
System.out.println(mainJson.get("Datastream").getAsJsonObject().get("#iot.id").getAsString());
This works fine for me using the com.google.gson.JsonObject library.
For the record, this is what i did.
import java.util.*;
public class DataObject {
public int Suggestions;
HashMap<String, route> routes = new HashMap<>();
//constructor
public DataObject(int mkr, String[][] routesArr){
Suggestions = mkr;
{
for (int i=0;i<Suggestions;i++){
routes.put("rank_"+(i+1),new route(routesArr[i]));
}
}
}
//class to populate the hashmap
public class route{
public String Origin;
public String Destination;
public String Weight;
public route(String arr[]){
String[] splitter = arr[0].split("-");
this.Origin = splitter[0];
this.Destination = splitter[1];
this.Weight = arr[1];
}
}
}
I am new to stackoverflow.
I am creating an Java application which it will get data from a web server. The data is in json format. Example"
[
{
"item_name": "Adame",
"item_type": "Special",
"item": "Chestplate",
"item_min_lvl": "50",
"enchantment": {
"health": "0.3",
"dam": "24%",
"life": "0.1",
"xp": "24%",
"loot": "22%"
},
"def": "73"
},
{
"item_name": "Sticks'",
"item_type": "Unique",
"item": "Stick",
"item_min_lvl": "4",
"enchantment": {
"health": "0.6",
"mana": "1",
"dam": "12%",
"life": "0.3",
"xp": "17%",
"loot": "17%"
},
"min_dam": "39",
"max_dam": "34"
}
]
I know how to deserialize json using Gson. As you can see, it's started with [. I never deserialize this case before. Also, the json data is not the same(e.g. enchantment). I also searched in Google but I can't find any similar case. Can anyone help me with the code?
Try with this code. You will get the answer of your question. It's an List with 2 items.
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new FileReader(new File("resources/json1.txt")));
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<MyJSON>>() {
}.getType();
List<MyJSON> list = gson.fromJson(builder.toString(), listType);
// you can try this form as well
// MyJSON[] list = gson.fromJson(builder.toString(), MyJSON[].class);
for (MyJSON json : list) {
System.out.println(json.toString());
}
...
class MyJSON {
String item_name;
String item_type;
String item;
String item_min_lvl;
Enchantment enchantment;
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("\nitem_name:").append(item_name);
builder.append("\nitem_type:").append(item_type);
builder.append("\nitem:").append(item);
builder.append("\nitem_min_lvl:").append(item_min_lvl);
builder.append("\n\nEnchantment Details:");
builder.append("\nhealth:").append(enchantment.health);
builder.append("\ndam:").append(enchantment.dam);
builder.append("\nlife:").append(enchantment.life);
builder.append("\nxp:").append(enchantment.xp);
builder.append("\nloot:").append(enchantment.loot);
return builder.toString();
}
}
class Enchantment {
String health;
String dam;
String life;
String xp;
String loot;
}
output:
item_name:Adame
item_type:Special
item:Chestplate
item_min_lvl:50
Enchantment Details:
health:0.3
dam:24%
life:0.1
xp:24%
loot:22%
item_name:Sticks'
item_type:Unique
item:Stick
item_min_lvl:4
Enchantment Details:
health:0.6
dam:12%
life:0.3
xp:17%
loot:17%
EDIT
The structure of each entry is not same hence you can't use POJO for this type of JSON.
Simply use ArrayList<Map<String, Object>> and access the value based on key from the map.
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Map<String, Object>>>() {
}.getType();
ArrayList<Map<String, Object>> list = gson.fromJson(builder.toString(), listType);
for (Map<String, Object> json : list) {
for (String key : json.keySet()) {
System.out.println(key + ":" + json.get(key));
}
System.out.println("===========");
}
output:
item_name:Adame
item_type:Special
item:Chestplate
item_min_lvl:50
enchantment:{health=0.3, dam=24%, life=0.1, xp=24%, loot=22%}
def:73
===========
item_name:Sticks'
item_type:Unique
item:Stick
item_min_lvl:4
enchantment:{health=0.6, mana=1, dam=12%, life=0.3, xp=17%, loot=17%}
min_dam:39
max_dam:34
===========
This is actually valid in Java and with GSON:
YourObject[] locs = gson.fromJson (someJsonString, YourObject[].class);
It'll parse and return an array of YourObject. Just create Java Classes that represent your JSON objects, and replace the placeholders as necessary.
EDIT:
As Braj said before, you can create a fully formed POJO, including the other, (non-symmetrical) attributes (I'm borrowing the code from from Braj's answer here):
//... snip ...
class MyJSON
{
String item_name;
String item_type;
String item;
String item_min_lvl;
Enchantment enchantment;
// Heres the other attributes
String min_dam;
String max_dam;
}
//... snip ...
GSON will parse it and set the values to null if they aren't provided in the original JSON.
However, from the other question, it seems that the JSON (Java - JSON Parser Error) for enchantment is provided inconsistently, so this will cause issues. I would recommend sending JSON for enchantment as an array for consistency, then you could structure your POJO as:
//... snip ...
class MyJSON
{
String item_name;
String item_type;
String item;
String item_min_lvl;
Enchantment[] enchantment;
// Heres the other attributes
String min_dam;
String max_dam;
}
//... snip ...
I have a Json Structure something like this
{
"name" : "abcd",
"details" : [{"city":"string", "zipcode":"integer"}],
"name" : "qwert",
"details" : [{"address":"long", "state":"string"}]
}
And my java code looks like below
public class JsonTest {
public static void main(String[] args) throws JsonParseException, IOException {
JsonFactory jf = new JsonFactory();
JsonParser jp = jf.createParser(new File("C:\\sample.json"));
while (jp.nextToken() != JsonToken.END_OBJECT)
{
String jsonField = jp.getCurrentName();
if ("name".equalsIgnoreCase(jsonField))
{
jp.nextToken();
System.out.println(jp.getText());
}
if ("details".equalsIgnoreCase(jsonField))
{
jp.nextToken();
while (jp.nextToken() != JsonToken.END_ARRAY)
{
jp.nextToken();
String field = jp.getText();
System.out.println(field);
}
}
}
}
}
All am trying to do is parse the whole json token by token and get the text. But the line while (jp.nextToken() != JsonToken.END_OBJECT) fails when it encounters a '}' in the array. Am just stuck here since yesterday and experimenting with several other tricks but nothing works out. Do we have another way doing this? Is my JSON structure looks okay? Please tell me where am going wrong. Thanks!
First of all:
[Doe]s my JSON structure look[s] okay?
Yes and no. while your JSON is legal, you are going to have a problem because of duplicate keys:
{
"name": "xxx",
"name": "yyy"
}
The behaviour of a JSON parser in this event is unpredictable, even RFC 7159 says so (yes, RFC 4627 has been superseded). Unfortunately, duplicate keys are still not forbidden.
So, it is legal, but not sane. Use an array instead:
[ { "name": "xxx", "details": "whatever" }, "etc" ]
This aside, reading JSON with Jackson is done as this:
final ObjectMapper mapper = new ObjectMapper();
final JsonNode node = mapper.readTree(yourFileHere);
You can then use the full power of JsonNode.
You cannot have fields with the same name in a json, well you can but it could not be parsed as in your case.
I assume you have an array of users with name and details fileds for each user.
Here is a candidate Java class corresponding to your User class:
public class TestUser implements Serializable {
String name;
List<Map<String, String>> details = new ArrayList<Map<String, String>>();
TestUser() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Map<String, String>> getDetails() {
return details;
}
public void setDetails(List<Map<String, String>> details) {
this.details = details;
}
}
with reverse engineering lets see how is a list of users are de-serialized;
public static void main(String[] args) throws IOException {
List<TestUser> testUsers = new ArrayList<TestUser>();
TestUser testUser1 = new TestUser();
testUser1.name = "abcd";
HashMap<String, String> detailsHashMap = new HashMap<String, String>();
detailsHashMap.put("city", "string");
detailsHashMap.put("zipcode", "integer");
testUser1.details.add(detailsHashMap);
testUsers.add(testUser1);
TestUser testUser2 = new TestUser();
testUser2.name = "qwert";
detailsHashMap = new HashMap<String, String>();
detailsHashMap.put("address", "long");
detailsHashMap.put("state", "string");
testUser2.details.add(detailsHashMap);
testUsers.add(testUser2);
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(testUsers));
}
and the outcome of the users list is:
[ {
"name" : "abcd",
"details" : [ {
"zipcode" : "integer",
"city" : "string"
} ]
}, {
"name" : "qwert",
"details" : [ {
"address" : "long",
"state" : "string"
} ]
} ]
As you can see it is different from your JSON string.
UPDATE
If you want to hold names and details in two separate containers...;
public static class Container {
List<String> names = new ArrayList<String>();
Map<String, String> details = new HashMap<String, String>();
public Container() {
}
public List<String> getNames() {
return names;
}
public void setNames(List<String> names) {
this.names = names;
}
public Map<String, String> getDetails() {
return details;
}
public void setDetails(Map<String, String> details) {
this.details = details;
}
}
....
public static void main(String[] args) throws IOException {
Container container = new Container();
container.names.add("abcd");
container.names.add("qwert");
container.details.put("city", "string");
container.details.put("zipcode", "integer");
container.details.put("address", "long");
container.details.put("state", "string");
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(container));
}
and the outcome JSON is;
{
"names" : [ "abcd", "qwert" ],
"details" : {
"address" : "long",
"zipcode" : "integer",
"state" : "string",
"city" : "string"
}
}