Java 如何将json转换为不提供参数名称的pojo
我正在尝试使用Jackson将JSON转换为java。但是没有得到正确的解决方案。我有一个JSON,里面没有参数名。我想使用PropertyOrder将json字段映射到POJO 我尝试了所有可能的方式进行类型引用,但没有得到我想要的结果 我的JSON类似于: {“1222”:[“乔”,26158],“1232”:[“根”,29168]} 以下是pojo:Java 如何将json转换为不提供参数名称的pojo,java,json,jackson,jackson-databind,Java,Json,Jackson,Jackson Databind,我正在尝试使用Jackson将JSON转换为java。但是没有得到正确的解决方案。我有一个JSON,里面没有参数名。我想使用PropertyOrder将json字段映射到POJO 我尝试了所有可能的方式进行类型引用,但没有得到我想要的结果 我的JSON类似于: {“1222”:[“乔”,26158],“1232”:[“根”,29168]} 以下是pojo: public class Employee{ int empId; EmployeeAtttribute employeeA
public class Employee{
int empId;
EmployeeAtttribute employeeAttribute;
}
@JsonProertyOrder({"name", "seq", "height"})
public class EmployeeAttribute{
String name;
int seq;
int height;
}
我希望得到使用JSON制作的Employee类列表
提前感谢。您的json将被解析为
Map
。
之后,您可以将
Map
转换为您的员工或更改json格式<代码>{“id”:1222,“attribute”:{“name”:“Joe”,“seq”:26,“height”:158}将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 ObjectMapper=newObjectMapper();Map jsonMap=objectMapper.readValue(readFile(pathToJsonFile),new TypeReference(){});嗯
@JsonPropertyOrder
用于在序列化pojo时,即在生成json时,定义属性的顺序。这不适用于你的情况。我不知道有任何基于注释的方法来定义该映射,因此您可能必须自己进行,例如通过自定义反序列化程序。不要将您尝试的代码放在注释、帖子中并放在那里。感谢您的输入。请查看TechFree给出的回复。它成功了。谢谢你的投入。请查看TechFree给出的回复。它成功了。你好,TechFree,{“1222”:[“Joe”,26158],“1232”:[“root”,29168],“emp_count”:“2”}在这种情况下,您的方法将得到支持。正如我所看到的,我们已经将它的值类型绑定为JsonFormat中的数组。如果我想忽略或使用emp_count(两种情况下),该怎么办。你能分享一下你的想法吗?我会用这个扩展的要求更新答案
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);
List<Employee> employee = new ArrayList<>();
for (Map.Entry<String, EmployeeAttribute> entry : map.entrySet()) {
employee.add(new Employee(Integer.valueOf(entry.getKey()),
entry.getValue()));
}
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();