如何在Java中构造类似于json的body对象?

我是Java编程的初学者,主要是javascript开发人员。我有一个js数组,

[
  {
    "key1": 0,"key2": 1,"key3": "string"
  },{
    "key1": 1,"key2": 2,"key3": "string2"
  }
]

如何在Java中构造相同的结构?

happyhappy2009 回答:如何在Java中构造类似于json的body对象?

根据要求,您需要按照以下步骤操作:

1)创建一个具有成员(键1,键2,键3)的Class

2)创建该类的对象并将其添加到List。 (正如您在评论中提到的,您必须对其进行迭代,最好使用ArrayList。)

第1步:

public class Data {

  private int key1;

  private int key2;

  private String key3;

  public Data(final int key1,final int key2,final String key3) {
    super();
    this.key1 = key1;
    this.key2 = key2;
    this.key3 = key3;
  }

  /**
   * @return the key1
   */
  public int getKey1() {
    return key1;
  }

  /**
   * @return the key2
   */
  public int getKey2() {
    return key2;
  }

  /**
   * @return the key3
   */
  public String getKey3() {
    return key3;
  }

  /**
   * @param key1
   *          the key1 to set
   */
  public void setKey1(final int key1) {
    this.key1 = key1;
  }

  /**
   * @param key2
   *          the key2 to set
   */
  public void setKey2(final int key2) {
    this.key2 = key2;
  }

  /**
   * @param key3
   *          the key3 to set
   */
  public void setKey3(final String key3) {
    this.key3 = key3;
  }

}

第2步:

public class Test {

  public static void main(final String[] args) {

    //Using List
    final List<Data> myDataList = new ArrayList<Data>();
    myDataList.add(new Data(0,1,"string"));
    myDataList.add(new Data(1,2,"string2"));

    // Or

    //Using Array
    final Data[] myData = {new Data(0,"string"),new Data(1,"string2")};


  }

}
, 如果您不关心类型(不推荐),则可以通过使用Map列表简单地创建

您可以尝试实现的目标。

List<Map<String,String>> myMap  = new ArrayList<Map<String,String>>();

但是,如果您认真使用Java,则需要了解有关面向对象编程的知识。您将需要创建一个具有强类型属性的类。 创建一个类之后,您可以创建一个数组,并用所述类(对象)的实例填充它。

,

选项1:地图列表。 不是类型安全的,因为我们没有声明确切的值类型。

List<Map<String,?>> list = List.of(
    Map.of(
        "key1","key2","key3","string"
    ),Map.of(
        "key1","string2"
    )
);

选项2: POJO数组。 类型安全,因为所有值均已明确输入。

MyObj[] array = { new MyObj(0,new MyObj(1,"string2") };
public class MyObj {
    private int key1;
    private int key2;
    private String key3;
    public MyObj() {
    }
    public MyObj(int key1,int key2,String key3) {
        this.key1 = key1;
        this.key2 = key2;
        this.key3 = key3;
    }
    public int getKey1() {
        return this.key1;
    }
    public void setKey1(int key1) {
        this.key1 = key1;
    }
    public int getKey2() {
        return this.key2;
    }
    public void setKey2(int key2) {
        this.key2 = key2;
    }
    public String getKey3() {
        return this.key3;
    }
    public void setKey3(String key3) {
        this.key3 = key3;
    }
}

列表vs数组当然可以任意选择,我只是想在那里显示两个选项。

,

您必须使用key1,key2和key3以及setter / getter创建Java类。之后,您可以从maven(如果使用maven项目)中使用Google gson gson artifact或Java的Json(jsonartifact)中使用

。 ,

首先,您必须创建一个具有变量key1,key2和key3的Java类。 然后使用Jackson库将Json解析为Java对象。

本文链接:https://www.f2er.com/3160985.html

大家都在问