我有以下代码的输出结果:
{"list":[{"x":"y"},{"a":"b"}]}
而我希望得到的输出结果是: [{"x":"y"},{"a":"b"}]
以下是代码。
而我希望得到的输出结果是: [{"x":"y"},{"a":"b"}]
以下是代码。
public class Test {
List<Map> list = new ArrayList();
public static void main(String [] args){
Test t = new Test();
Map m1 = new HashMap();
m1.put("x","y");
t.list.add(m1);
Map m2 = new HashMap();
m2.put("a","b");
t.list.add(m2);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(Include.NON_EMPTY);
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.NON_PRIVATE);
Writer writer = new StringWriter();
try {
objectMapper.writeValue(writer, t);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("The json is:\n"+writer.toString());
}
}
这个问题的更新 - 进一步处理 会给我:
{"list":[{"map":{"x":"y","x1":"y1"}},{"map":{"a1":"b1","a":"b"}}]}
我想要的是[{"x":"y","x1":"y1"},{"a1":"b1","a":"b"}]
public class Test {
public class Car{
Map map = new HashMap();
}
List<Car> list = new ArrayList();
public static void main(String [] args){
Test t = new Test();
Test.Car car = t.new Car();
Map m1 = new HashMap();
m1.put("x","y");
m1.put("x1","y1");
car.map = m1;
t.list.add(car);
car = t.new Car();
Map m2 = new HashMap();
m2.put("a","b");
m2.put("a1","b1");
car.map = m2;
t.list.add(car);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(Include.NON_EMPTY);
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.NON_PRIVATE);
Writer writer = new StringWriter();
try {
objectMapper.writeValue(writer, t);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("The json is:\n"+writer.toString());
}
}
objectMapper.writeValue(writer, t.list)
呢? - Jon SkeetList<Car>
创建一个List<Map<...>>
。不过也可能有一种方式可以配置Jackson来自动完成这个过程——你应该将此示例添加到你的问题中,以便说明你想要做什么。否则,“只需序列化t.list
”的方法是最明显的方法。 - Jon Skeet