【发布时间】:2016-01-09 07:43:30
【问题描述】:
我从代码中得到以下输出: {"list":[{"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)? -
说我有 List
并且 Car 有一张地图——然后呢?如何忽略地图但只打印 [ {"x","y"},{...}] 之类的名称值? -
最简单的解决方法是从
List<Car>创建一个List<Map<...>>。不过,可能有一种方法可以将 Jackson 配置为自动为您执行此操作 - 您应该将该示例添加到您的问题中,作为您想要执行的操作的示例,否则“仅序列化t.list”方法是最明显的一种。 -
我不想重做响应,尤其是因为它是固定的并且它们可能很大。我希望序列化处理这个问题,所以这是一次。还根据您的建议编辑了问题。