【问题标题】:Json display name of objects in listJson 显示列表中对象的名称
【发布时间】:2015-10-02 12:34:33
【问题描述】:

我正在使用 spring mvc 返回一个 Tagset JSON 对象。我有以下两个 java 对象

public class Tagset {   
    private String tag;
    private String tagDisplayName;
    private List<Case> caseList;
}

public class Case { 
    private String title;
    private String url;
}

我得到的回应是:

{"tag":"Bluetooth",
 "tagDisplayName":"Bluetooth 101",
 "caseList":[
            {"title":"How do I update my Bluetooth?",
             "url":"https://test.test.com"},
            {"title":"How do I delete my Bluetooth?",
             "url":"https://test.test.com"}
            ]
}

我希望为每个案例对象显示案例名称:

{"tag":"Bluetooth",
 "tagDisplayName":"Bluetooth 101",
 "caseList":[
            case:{"title":"How do I update my Bluetooth?",
             "url":"https://test.test.com"},
            case:{"title":"How do I delete my Bluetooth?",
             "url":"https://test.test.com"}
            ]
}

【问题讨论】:

  • 您可能会发现这很有帮助stackoverflow.com/questions/2435527/…
  • case 应该加引号吧?
  • 即使我们可以将 obj 类型 "case" 添加到 "caseList" 中,也没有必要迭代 JSON obj。 caseList[i].title 将给出与 caseList[0].case.title 相同的结果。此外,如果您的对象增长到更大的数据集,从服务器传输到 UI 的数据量将增加多方面,因此使您的 JSON 输出尽可能少,并且只输出所需的数据。

标签: java json spring-mvc


【解决方案1】:

你愿意拥有的都是可能的,但它不会再是json body。为此,您可以编写自定义序列化程序和反序列化程序。

【讨论】:

    【解决方案2】:

    请尝试为Case类添加以下代码行;

    @JsonTypeInfo(include=As.WRAPPER_OBJECT, use=Id.NAME)
    

    这是 Jackson API 的一部分。通过添加上面的行,我可以生成输出;

    {
      "tag" : "Bluetooth",
      "tagDisplayName" : "Bluetooth 101",
      "caseList" : [ {
        "Case" : {
          "title" : "How do I update my Bluetooth?",
          "url" : "https://test.test.com"
        }
      }, {
        "Case" : {
          "title" : "How do I delete my Bluetooth?",
          "url" : "https://test.test.com"
        }
      } ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      相关资源
      最近更新 更多