在java中为json响应添加其他属性

jjhzyzn0  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(299)

我有一个以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"
}

但我需要另一份名单放在这里。iw低于输出

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

为了 subCategory 属性我还有一个类似于samplelist.java的类。我可以得到每个类别对应的子类别。有人能帮我得到预期的回应吗?
我不想碰我的samplelist类。

bn31dyow

bn31dyow1#

你必须扩展你的班级样本列表

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

当然,在返回列表之前,必须在samplelist项中设置正确的子类别。
如果你不想破坏你的samplelist类,当然你可以添加一层dto对象并在它们之间Map,或者直接操作响应,比如用responsebodyadvice

1sbrub3j

1sbrub3j2#

方法:1

public class SampleList
{
    private Integer categoryId;
    private String categoryName;

    // Getter and Setter
}

public class SampleList2
{
   private String name;
   // Getter and Setter
}

//在不Map两个不同类的情况下获取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
}

//上面提到的Map两个类的逻辑

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());
}

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

相关问题