在Java中为JSON响应添加附加属性



我有一个返回JSON格式列表的服务。请查看下面的代码:

public List<SampleList> getValues() {
List<SampleList> sample = null;
sample= DAOFactory.sampleDAO.findByCriteria().add(Restrictions.isNull("endDate")).list();
return sample;
}
Class SampleList.java
public class SampleList {
private Integer categoryId;
private String  categoryName;
//getter setter 
}

现在我的服务返回如下JSON

{
categoryId : 1,
categoryName : "Test"
}

但是我需要在这里封装另一个列表。我希望下面的输出

{
categoryId : 1,
categoryName : "Test"
subCategory:
{
name: ""
} 
}

对于subCategory属性,我有另一个类似于SampleList.java的类。我可以得到对应于每个类别的子类别。有人能帮助我得到预期的回应吗?

我不想碰我的SampleList类。

您必须扩展您的类SampleList

Class SampleList.java
public class SampleList {
private Integer categoryId;
private String  categoryName;
private SubCategory subCategory;
//getter setter 

在您返回列表之前,当然您必须在SampleList项中设置正确的子类别。

如果你不想破坏你的SampleList类,当然你可以添加一层DTO对象并在它们之间进行映射,或者直接操作响应,例如使用ResponseBodyAdvice

方法:1

public class SampleList
{
private Integer categoryId;
private String categoryName;
// Getter and Setter
}
public class SampleList2
{
private String name;
// Getter and Setter
}

//逻辑获取JSON值,而不映射两个不同的类

private void getJsonValue() throws JsonProcessingException, JSONException
{
SampleList sampleList = new SampleList();
sampleList.setCategoryId(1);
sampleList.setCategoryName("cat 1");

String sampleListJson = new ObjectMapper().writeValueAsString(sampleList);

SampleList2 sampleList2 = new SampleList2();
sampleList2.setName("Sub category");

String valueOfSample2 = new ObjectMapper().writeValueAsString(sampleList2);

JSONObject sampleListJsonObj = new JSONObject(sampleListJson); // for class SampleList
JSONObject sampleList2JsonObj = new JSONObject(valueOfSample2); // for class SampleList2

sampleListJsonObj.put("subCategory", sampleList2JsonObj);

System.out.println(sampleListJsonObj.toString());
}

方法:2

public class SampleList
{
private Integer categoryId;
private String categoryName;
private SampleList2 subCategory;
// Getter and Setter
}
public class SampleList2
{
private String name;
// Getter and Setter
}

//上面提到的映射两个类的逻辑

private static void getJsonValue() throws JsonProcessingException
{
SampleList sampleList = new SampleList();
sampleList.setCategoryId(1);
sampleList.setCategoryName("cat 1");

SampleList2 sampleList2 = new SampleList2();
sampleList2.setName("Sub category");

sampleList.setSubCategory(sampleList2);

String jsonString = new ObjectMapper().writeValueAsString(sampleList);

System.out.println(jsonString.toString());
}

如果您对此有任何问题,请告诉我。

谢谢。

最新更新