如何在Java8中创建Json数组,并且仅在设置值的情况下才打印json?

时间:2018-12-19 16:47:03

标签: java arrays json jackson

我正在尝试使用fasterxml jackson来生成以下内容。但是我被卡住了。我似乎无法弄清楚如何创建数组。

{
   "setAccId":"12345",
   "groupOf":null,
   "isEnabled":false,
   "list":[
      {
         "student":"jim",
         "type":"S_A",
         "retro":null
      },
      {
         "student":"bob",
         "type":"S_A",
         "retro":null
      }
   ],
   "sort":[]
}

我有两节课。一个具有Json属性,另一个具有我在其中打印的位置。

  

下面的类(DynamicJsonHelper)是我拥有所有json属性的地方

package com.company.jsonfc;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonPropertyOrder({
"accId",
"groupOf",
"isEnabled"
})

public class DynamicJsonHelper {

    public String accId;
    public String groupOf;
    public List studentList;

    @JsonProperty("accId")
    public void setAccId(String accId) {
        this.accId = accId;
    }

    @JsonProperty("groupOf")
    public void setGroupOf(String groupOf) {
        this.groupOf = groupOf;
    }

    @JsonProperty("isEnabled")
    public boolean isEnabled() {
        return false;
    }

    @JsonProperty("studentList")
    public List<StudentList> studentList() {
        return studentList;
    }

}
  

学生名单类(根据建议)

class StudentList {
    String student;
    String type;
    String retro; 
}
  

这是我称之为的类(PrintJson)。

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;

import com.company.jsonfc.DynamicJsonHelper;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class PrintJson {

    @Test
    public void create_json() throws JsonProcessingException {
    final JsonNodeFactory factory = JsonNodeFactory.instance;

    DynamicJsonHelper dynamicJsonHelper = new DynamicJsonHelper();
    String jsonString;
    ObjectMapper mapper = new ObjectMapper();

    dynamicJsonHelper.setAccId("12345");

    jsonString = mapper.writeValueAsString(dynamicJsonHelper);
    System.out.println(jsonString);
    }

}
  

这将导致打印以下内容:

{
   "setAccId":"12345",
   "groupOf":null,
   "isEnabled":false
   "studentList":null
}

1)如何在末尾添加列表:[...]数组和排序:[]?

2)在PrintJson类中,我没有为groupOf设置值,但仍在Json中创建。如何设置它,以便在设置值时将其打印..否则它不包含在正在打印的json中。

如果您接受了我的代码并提供了基于它的示例以更好地理解,我将不胜感激

2 个答案:

答案 0 :(得分:1)

您错过了必须具有第三类的知识,并且该类必须具有java.util.List类型或示例的数组和名称列表的属性。

例如

public class JsonHolder {
    // appropriate Json/Jackson annotations ommitted

     private String  setAccId;
     private String  groupOf;
     private boolean isEnabled;
     private List<DynamicJsonHelper>  list;
     private String[] sort;

     // .. getter/setters ...

}

然后,您必须创建该对象,并在创建DynamicJsonHelper时将其放入列表或数组中。

毕竟,您可以序列化JsonHolder对象,并且您会看到Java List或Array为JSON数组。

UPD:仅需注意,在{ ... }之类的JSON结构中,它是一个对象,而在Java中,必须为其提供一个类。

所以,从您发布的JSON结构开始

{
  "setAccId":"12345",
  "groupOf":null,
  "isEnabled":false,
  "list":[
   {
     "student":"jim",
     "type":"S_A",
     "retro":null
  },
  {
     "student":"bob",
     "type":"S_A",
     "retro":null
  }
 ],
 "sort":[]
}

它是一个对象(将其命名为JsonHolder),其属性名为setAcctId, groupOf, isEnabled, list, sort 因此,您必须为此使用一个Java类(类似于您对DynamicJsonHelper所做的操作。您可以使用任何@Json注释以相同的方式使用(我省略了它们,留给了您)。默认情况下,Jackson或其他JSON序列化程序将不会使用它们。

我的意思是说您的@JsonProperty(“ accId”)

@JsonProperty("accId")
public void setAccId(String accId)
只要名为getAcctId,setAcctId,acctId的getter / setter / property,也不需要

。如果没有@JsonProperty批注,Jackson将使用它。

顺便说一句,最好这样做,就像代码可读性一样。 :-)

根据您的问题: JSON中的listsort属性是数组。 Jackson将Java集合类(例如List,Set或Arrays)解析为JSON数组。

然后根据所需的JSON结构list属性,是您创建的DynamicJsonHelper对象的此类集合。在Java类中,列表或数组只是您的选择-使用更适合您的内容。我建议使用列表而不是数组。在Java中使用数组不是一个好主意。 :-)

到目前为止,您仅为必须具有DynamicJsonHelper对象的list属性的对象创建了Java类JsonHolder。剩下的就是创建该“ JsonHolder”类,并将该对象提供给Jackson以将其序列化为所需的JSON结构。

有一堆@Json批注,您可以使用它们来允许或禁止使用null或为空值,更改属性名称,排除要序列化的Java类属性,依此类推,等等...一切取决于您...祝你好运!

答案 1 :(得分:1)

  

1)如何在末尾添加列表:[...]数组和排序:[]?

答案:您可以再创建两个类,一个用于list,一个用于sort。现在,在类DynamicJsonHelper中,您可以像添加accIdisEnabled一样添加它们两者 然后将它们打印出来。确保在两个类中都将您想要的字段添加为实例变量。例如,对于列表,您可以有一个类似的类:

class StudentList{
    String student;
    String type;
    String retro;
}

现在在您的课程DynamicJsonHelper中将字段添加为List<StudentList>。同样,您可以为sort做。

  

2)在PrintJson类中,我没有为groupOf设置值,但是它仍然是   在Json中创建。如何设置它,如果我设置了值,它就会被打印出来。   否则它不包含在正在打印的json中。

答案:您可以 使用对象映射器,并将其设置为在序列化期间忽略空字段。例如:mapper.setSerializationInclusion(Include.NON_NULL); ,您可以在类级别将其设置为忽略空值(如果有)。例如:

@JsonInclude(Include.NON_NULL)
class Test
{
  String t;
}

如上面的aBnormaLz的注释中所述,如果类型像isEnabled那样是原始类型,则无法使用。因此,请考虑将其更改为布尔值,并确保其他字段也是如此。

编辑:

@JsonPropertyOrder({
"accId",
"groupOf",
"isEnabled"
})
@JsonInclude(JsonInclude.Include.NON_NULL)

public class DynamicJsonHelper {

public String accId;
public String groupOf;
public List<Student> studentList;

@JsonProperty("accId")
public void setAccId(String accId) {
    this.accId = accId;
}

@JsonProperty("groupOf")
public void setGroupOf(String groupOf) {
    this.groupOf = groupOf;
}

@JsonProperty("isEnabled")
public boolean isEnabled() {
    return false;
}

@JsonProperty("studentList")
public void setStudentList(List<Student> list) {
    this.studentList = list;
}

}

class Student {
private String student;
private String type;
private String retro; 

public Student(String student, String type, String retro) {
    this.student = student;
    this.type = type;
    this.retro = retro;
}

public String getStudent() {
    return student;
}

public void setStudent(String student) {
    this.student = student;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public String getRetro() {
    return retro;
}

public void setRetro(String retro) {
    this.retro = retro;
}    
}

class HelperTest{

public static void main(String[] args) throws JsonProcessingException {
    DynamicJsonHelper dynamicJsonHelper = new DynamicJsonHelper();
    String jsonString;
    ObjectMapper mapper = new ObjectMapper();

    dynamicJsonHelper.setAccId("12345");

    List<Student> list = Arrays.asList(new Student("s1", "t1", "r1"), new Student("s2", "t2", "r2"));

    dynamicJsonHelper.setStudentList(list);
    jsonString = mapper.writeValueAsString(dynamicJsonHelper);
    System.out.println(jsonString);

}
}

执行程序后,output如下所示:

{
   "accId": "12345",
   "isEnabled": false,
   "studentList": [
                    {
                      "student": "s1",
                      "type": "t1",
                      "retro": "r1"
                    },
                    {
                      "student": "s2",
                      "type": "t2",
                      "retro": "r2"
                    }
                   ]
}