【发布时间】:2026-02-14 13:25:01
【问题描述】:
我正在编写一个spring-boot 应用程序,我的控制器应该返回JSON。
我的模特:
public class Category {
private String name;
private List<Category> subCategory;
//getters, setters, constructors
}
为此模型填充的测试/数据:
@Test
public void testCategory() throws JsonProcessingException {
Category city1 = new Category("London",null);
Category city2 = new Category("Leeds",null);
Category country = new Category("UK",Arrays.asList(city1,city2));
Category continent = new Category("Europe", Arrays.asList(country));
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
System.out.println( mapper.writeValueAsString(continent));
}
这会产生如下输出:
{
"name" : "Europe",
"subCategory" : [ {
"name" : "UK",
"subCategory" : [ {
"name" : "London",
"subCategory" : null
}, {
"name" : "Leeds",
"subCategory" : null
} ]
} ]
}
期望的输出(忽略格式,除了每个子类别应该缩进):
{
"Europe": {
"UK": {
"London": {},
"Leeds": {}
}
}
}
这是我原来的问题。
我尝试了一些东西,例如Map<String,Object> 和subcategory,它可以工作,但它会产生输出,其中London 和Leeds 被包裹在[] 中。我不能让那些回复客户。
编辑:
如果我使用基于地图的方法:
@Test
public void testCategory2() throws JsonProcessingException {
Map<String,Object> leeds = Map.of("Leeds",new HashMap<>());
Map<String,Object> london = Map.of("London",new HashMap<>());
MultiValuedMap<String, Object> uk = new HashSetValuedHashMap<>();
uk.put("UK",london);
uk.put("UK",leeds);
Map<String,Object> europe = Map.of("Europe", uk.asMap());
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(europe);
System.out.println(json);
}
输出:
{
"Europe" : {
"UK" : [ {
"London" : { }
}, {
"Leeds" : { }
} ]
}
}
【问题讨论】:
-
您想要的输出不是有效的 JSON。也许您忘记了开头的 { 和结尾的 }?如果您的客户真的期望某些不是有效的 JSON,您将无法使用 Jackson 来满足它。
-
@neofelis,谢谢,是的,我失踪了。编辑以反映正确的 Json。
标签: java json spring spring-boot serialization