猿问

如何以 Json 格式显示包含员工和多个地址的地图

我创建了两个类 Employee 和 Address 并且对于每个员工都会有多个地址。我想以 JSON 格式显示这些地址。我在下面尝试了一些代码。您能告诉我如何更改代码以按以下格式显示地图值吗?同样,我想显示 ID 为 2 的员工。


{

 id: 1

 name: John

 Addresses: [

  {

   addrLine1:StreetABC Line 1

   addrLine2: StreetABC Line 2

   city:CityABC

   zip: ZipABC

  },

  {

   addrLine1:StreetXYZ Line 1

   addrLine2: StreetXYZ Line 2

   city:CityXYZ

   zip: ZipXYZ

  }

 ]

}

这是Test.class;


import java.util.*;


import com.fasterxml.jackson.core.type.TypeReference;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.json.JSONObject;


public class Test {

    public static void main(String args[]) {

        ObjectMapper mapper = new ObjectMapper();


        Employee e1= new Employee(1,"John");

        Employee e2= new Employee(2,"Robert");


        Address a1 = new Address ("StreetABC Line 1","StreetABC Line 2", "CityABC","ZipABC");

        Address a2 = new Address ("StreetXYZ Line 1","StreetXYZ Line 2", "CityXYZ","ZipXYZ");

        Address a3 = new Address ("StreetLMN Line 1","StreetLMN Line 2", "CityLMN","ZipLMN");

        Address a4 = new Address ("StreetJQK Line 1","StreetJQK Line 2", "CityJQK","ZipJQK");


        List<Address> address1=new ArrayList<Address>();

        List<Address> address2=new ArrayList<Address>();

        List<Employee> employees = new ArrayList<Employee>();


        employees.add(e1);

        employees.add(e2);



        address1.add(a1);

        address1.add(a2);


        address2.add(a3);

        address2.add(a4);


        Map<Employee, List<Address>> employeeAddressmap=new HashMap<Employee, List<Address>>();



        employeeAddressmap.put(e1,address1);

        employeeAddressmap.put(e2,address2);


        try {

            mapper.writeValueAsString(employeeAddressmap);

        } catch (Exception e) {

            e.printStackTrace();

        }



    }

}

Employee.class 喜欢 ;


class Employee{


    private int id;

    private String name;


    public Employee(int id, String name) {

        this.id = id;

        this.name = name;

    }


    public void setId(int id){

        this.id=id;

    }


胡子哥哥
浏览 131回答 1
1回答
随时随地看视频慕课网APP

相关分类

Java
我要回答