首页 > 解决方案 > 如何将json转换为没有给出参数名称的pojo

问题描述

我正在尝试使用 Jackson 将 JSON 转换为 java。但没有得到适当的解决方案。我有 JSON,其中没有参数名称。我想使用 PropertyOrder 将 json 字段映射到 POJO。

我以所有可能的方式尝试了类型引用,但未能得到我想要的结果。

我的 JSON 是这样的: {"1222": ["Joe", 26, 158],"1232": ["root", 29, 168] }

以下是pojo:

public class Employee{
    int empId;
    EmployeeAtttribute employeeAttribute;
}

@JsonProertyOrder({"name", "seq", "height"})  
public class EmployeeAttribute{     
    String name;  
    int seq;  
    int height;  
}  

我正在寻找使用 JSON 制作的 Employee 类列表。

提前致谢。

标签: javajsonjacksonjackson-databind

解决方案


将 EmployeeAttribute 类注释为:

@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 + "]";
    }
}

您可以使用此代码将您的 JSON 转换为对象(地图):

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);

进一步将其转换为 Employee 列表:

 List<Employee> employee = new ArrayList<>();
 for (Map.Entry<String, EmployeeAttribute> entry : map.entrySet()) {
       employee.add(new Employee(Integer.valueOf(entry.getKey()), 
  entry.getValue()));
 }

对于输入 JSON 字符串包含 'emp_count' 键的扩展要求,由于输入不能真正解析为 Java 对象模型,因此可以使用这种方法读取该元素并将其删除,以便按照原始逻辑进行解析会像以前一样工作,并且“emp_count”仍然被读取/提取。根据需要进行优化:

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();

推荐阅读