How to Convert Linkedhashmap to Custom Java Object

how to convert LinkedHashMap to Custom java object?

You need to do this:

List<ConsultantDto> myObjects =
mapper.readValue(jsonInput, new TypeReference<List<ConsultantDto>>(){});

(From this SO answer)

The reason you have to use TypeReference is because of an unfortunate quirk of Java. If Java had a proper generics, I bet your syntax would have worked.

Casting LinkedHashMap to Complex Object

You can use ObjectMapper.convertValue(), either value by value or even for the whole list. But you need to know the type to convert to:

POJO pojo = mapper.convertValue(singleObject, POJO.class);
// or:
List<POJO> pojos = mapper.convertValue(listOfObjects, new TypeReference<List<POJO>>() { });

this is functionally same as if you did:

byte[] json = mapper.writeValueAsBytes(singleObject);
POJO pojo = mapper.readValue(json, POJO.class);

but avoids actual serialization of data as JSON, instead using an in-memory event sequence as the intermediate step.

How can I convert List of LinkedHashMap to List of Custom Object using Java 8

Create a stream over the source list. And transform every map in the list into an instance of Employee using the values mapped to the keys "name" and "designation".

public static void main(String[] args) {
List<Map<String, String>> source = List.of(
Map.of("name","David", "designation","Senior Software Engineer"),
Map.of("name","Alex", "designation","Software Engineer"),
Map.of("name","Jessi","designation","Lead"),
Map.of("name","Martin","designation","Manager"));

List<Employee> result = source.stream()
.map(map -> new Employee(map.get("name"), map.get("designation")))
.collect(Collectors.toList());

result.forEach(System.out::println);
}

Output

Employee{name='David', designation='Senior Software Engineer'}
Employee{name='Alex', designation='Software Engineer'}
Employee{name='Jessi', designation='Lead'}
Employee{name='Martin', designation='Manager'}

Note:

  • It's not a good practice to store an object as a map. In your example, nothing can save you from typo, and you will get null instead of an attribute value.
  • Don't drop the generic information.

Convert LinkedHashMap<String,String> to an object in Java

You can create two classes

@XmlAccessorType(XmlAccessType.FIELD) 
public class Document {
@XmlElement
private String title;
@XmlElement
private String id;
@XmlElement
private int version;
}


@XmlAccessorType(XmlAccessType.FIELD)
public class MapJson {
@XmlElement
private LinkedHashMap<String, String> documents;
}

and cobvert Object to JSON usingg

Jackson

new org.codehaus.jackson.map.ObjectMapper().writeValueAsString(instanceofMapJson);  

Google JSON

new com.google.gson.Gson().toJson(instanceofMapJson);  

PS. Using google json, you can remove xml annotations from your classes

Converting LinkedHashMap<String,MyClass> to Java Object

The json you posted would not deserialize into a map of SummaryResponse objects, but rather an individual SummaryResponse object. To make your binding work, you would have to have json that looked something like this:

{
...
'summary': {
'summary1': {"totalMR":4.599000000000903E12,"totalMA":1.9174920000386694E11,"totalQA":5.1111111181E9,"totalQR":1.000020666115264E11}
'summary2': {"totalMR":4.599000000000903E12,"totalMA":1.9174920000386694E11,"totalQA":5.1111111181E9,"totalQR":1.000020666115264E11}
}
...
}

Alternatively, if you need to make your Java class conform to the json you provided, you simply need to change the declaration of summary:

private SummaryResponse summary;

How to convert a LinkedHashMap<String, List<Node>> into a JSONObject?

I solved it combining JSONArray and JSONObject class.

I've created the main object using a loop for all the nodes:

for (Node node : nodeList)
{
try
{
JSONObject obj = new JSONObject();
obj.put("value", node.getValue());
obj.put("label", node.getLabel());
jsonArrayOne.put(obj)
}
catch (JSONException e)
{
log.info("JSONException");
}
}

Then put the jsonArrayOne in a jsonObject:

jsonObjOne.put("items", jsonArrayOne);

And put this jsonObjOne into an jsonArray:

jsonArrayTwo.put(jsonObjOne);

Put this jsonArrayTwo in a jsonObject:

jsonObjTwo.put(element, jsonArrayTwo);

Finally put this jsonObjTwo into the jsonArrayFinal.

jsonArrayFinal.put(jsonObjTwo);

At the end I converted the jsonArrayFinal into a String:

jsonArrayFinal.toString();

How to Convert some custom Map object to LinkedHashMap?

You will need to perform a couple of conversion steps.

  1. Convert all Address objects to LinkedHashMap objects.
  2. Put all Map entries into a LinkedHashMap object.

For 1st one, you can write a utility method some where that can do this conversion. For example,

public static List<LinkedHashMap> addresstoMap(List<Address> addresses)
{
List<LinkedHashMap> list = new ArrayList<>();
for(Address a: addresses){
LinkedHashMap map = new LinkedHashMap();
// Add address fields to map here
list.add(map);
}
return list;
}

Then, for the 2nd step, you can do this:

LinkedHashMap<String, List<LinkedHashMap>> map = new LinkedHashMap<?,?>();

iterate through the entry sets of mapObj and put them into the above map object.

for (Map.Entry<String, List<Address>> e : m.entrySet()) {
map.put(e.getKey(), addresstoMap(e.getValue()));
}

The final map object above will contain the correct representation in the LinkedHashMap<String, List<LinkedHashMap>> datatype.

Hope this helps!



Related Topics



Leave a reply



Submit