Json Object包含2个相同类型的嵌套对象

时间:2014-09-17 11:18:23

标签: java json

我有一个非常简单的问题似乎没有答案。

我有一个对象,里面有两个相同类型的对象,它们不是数组。我如何在json中表示它?

GroupOfEmployees{

Employee emp1;
Employee emp2;
}

Employee{
String name;
int id;
}

emp1详情: 名称:第一 id:1

emp2详情: 名字:第二 ID:2

2 个答案:

答案 0 :(得分:1)

如果您正在寻找代表GroupOfEmployees对象的json对象,那么示例json将如下所示

{
    "emp1": {
        "name": "name1",
        "id": 1
    },
    "emp2": {
        "name": "name2",
        "id": 2
    }
}

更新
当您将上面的json转换为对象时,您将获得一个对象,该对象包含名为emp1&的两个雇员对象。 EMP2。请考虑以下示例

以下是您的员工类:

public class Employee {
    private String name;

    private int id;

    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }

    // getter & setter methods

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Employee [name=");
        builder.append(name);
        builder.append(", id=");
        builder.append(id);
        builder.append("]");
        return builder.toString();
    }
}

以下是GroupOfEmployees类:

public class GroupOfEmployees {
    private Employee emp1;
    private Employee emp2;

    // getters & setters method

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("GroupOfEmployees [emp1=");
        builder.append(emp1);
        builder.append(", emp2=");
        builder.append(emp2);
        builder.append("]");
        return builder.toString();
    }
}

这里有主要方法:

public static void main(String[] args) {
    Employee emp1 = new Employee("name1", 1);
    Employee emp2 = new Employee("name2", 2);

    GroupOfEmployees groupOfEmployees = new GroupOfEmployees();
    groupOfEmployees.setEmp1(emp1);
    groupOfEmployees.setEmp2(emp2);

    Gson gson = new GsonBuilder().create();

    String jsonValue = gson.toJson(groupOfEmployees);
    System.out.println("jsonValue = " + jsonValue);

    GroupOfEmployees newGroup = gson.fromJson(jsonValue, GroupOfEmployees.class);
    System.out.println("Object value = " + newGroup);
}

最后输出是:

jsonValue = {"emp1":{"name":"name1","id":1},"emp2":{"name":"name2","id":2}}
Object value = GroupOfEmployees [emp1=Employee [name=name1, id=1], emp2=Employee [name=name2, id=2]]

答案 1 :(得分:1)

制作JSONArray

[
{
name: "name1",
id: = id1 }, 
{
name: "name2",
id: = id2 }
]