I am trying to convert JSON to java using Jackson. But not getting proper solution. I have JSON which does not have parameter name in it. I want to use PropertyOrder to map json fields to POJO.
I tried type reference in all possible ways but failed to get my desired result.
My JSON is like : {"1222": ["Joe", 26, 158],"1232": ["root", 29, 168] }
Below are the pojo:
public class Employee{
int empId;
EmployeeAtttribute employeeAttribute;
}
@JsonProertyOrder({"name", "seq", "height"})
public class EmployeeAttribute{
String name;
int seq;
int height;
}
I am looking to get List of Employee class made using JSON.
Thanks in Advance.
Annotate EmployeeAttribute class as:
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
@JsonPropertyOrder({"name", "seq", "height"})
public class EmployeeAttribute
{
public String name;
public int seq;
public int height;
@Override
public String toString()
{
return "EmployeeAttribute [name=" + name + ", seq=" + seq + ", height=" + height + "]";
}
}
You can use this code to convert your JSON to Object (map):
ObjectMapper mapper = new ObjectMapper();
String jsonInput = "{\"1222\": [\"Joe\", 26, 158],\"1232\": [\"root\", 29, 168] }";
TypeReference<Map<String, EmployeeAttribute>> typeRef =
new TypeReference<Map<String, EmployeeAttribute>>()
{
};
Map<String, EmployeeAttribute> map = mapper.readValue(jsonInput, typeRef);
map.values().iterator().forEachRemaining(System.out::println);
Further convert this to a list of Employee:
List<Employee> employee = new ArrayList<>();
for (Map.Entry<String, EmployeeAttribute> entry : map.entrySet()) {
employee.add(new Employee(Integer.valueOf(entry.getKey()),
entry.getValue()));
}
To the extended requirement where the input JSON string contained 'emp_count' key, since the input is not really parseable to a Java Object model, this approach can be used which reads this element, and removes it, so that parsing as per the original logic would work as before and the 'emp_count' is still read/extracted. Optimize as required:
String jsonInput = "{\"1222\": [\"Joe\", 26, 158],\"1232\": [\"root\", 29, 168], \"emp_count\" : \"2\"}";
JsonNode node = mapper.readTree(jsonInput);
if (node.has("emp_count")) {
int employeesInArray = ((ObjectNode) node).remove("emp_count").asInt();
System.out.println("Num of employees in array: " + employeesInArray);
} else {
System.out.println("Num of employees was not provided, missing emp_count element");
}
//updated JSON input String, that works as before
jsonInput = node.toString();