使用Map和Normal对象映射JSON

时间:2017-07-12 21:12:06

标签: java json hashmap jackson

我正在关注JSON

{  
   'routers':
      {  
         'external_gateway_info':{  },
         'description':'',
         'gw_port_id':'1f290c84-02fe-4bdb-a063-77a425cc10f5',
         'tenant_name':'lmco-test'
      },
     'tenants':{  
          '82d1df3fcfc14ac594c6f5c5b6dcad6a':'lmco-test',
          '6eb4b2dd40dc4d63a3c8a691c371dd06':'admin',
          '10b0726823784ceca219821d44a2b5d1':'ivs-perf',
          'VRRP_Service':'VRRP_Service',
          '8fb76703c3084308a01d113751560730':'service'
      }
}

现在路由器是一个简单的对象,我将键/值映射到我的类Routers.java,但租户是HashMap。 我无法找到一种方法,我可以使用单个映射器将路由器和租户映射到单个对象

我的映射器

JSONObject jsonData = new JsonRepresentation(entity).getJsonObject();
RootModel rootModel = mapper.readValue(jsonData.toString(), RootModel.class);

Root.java片段

public class RootModel {

    private Router routers;
    private Tenant tenants;


    public RootModel(@JsonP
...
...
}

2 个答案:

答案 0 :(得分:0)

您的路由器类就像,

class Router {

    private String external_gateway_info;
    private String description;
    private String gw_port_id;
    private String tenant_name;

    public String getExternal_gateway_info() {
        return external_gateway_info;
    }

    public void setExternal_gateway_info(String external_gateway_info) {
        this.external_gateway_info = external_gateway_info;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getGw_port_id() {
        return gw_port_id;
    }

    public void setGw_port_id(String gw_port_id) {
        this.gw_port_id = gw_port_id;
    }

    public String getTenant_name() {
        return tenant_name;
    }

    public void setTenant_name(String tenant_name) {
        this.tenant_name = tenant_name;
    }

}

你的 RootModel 就像,

class RootModel {

    private Router routers;
    private HashMap<String, String> tenants;

    public Router getRouters() {
        return routers;
    }

    public void setRouters(Router routers) {
        this.routers = routers;
    }

    public HashMap<String, String> getTenants() {
        return tenants;
    }

    public void setTenants(HashMap<String, String> tenants) {
        this.tenants = tenants;
    }

}

只需将您的租户转换为HashMap,它就能正常运行。希望这会对你有所帮助。

答案 1 :(得分:0)

显然没有更简洁的方法可以将这种数据用于一种地图。我做了什么,我使用两个不同的映射器来映射路由器和租户。