【问题标题】:Get jersey/jackson json into several classes将 jersey/jackson json 分成几个类
【发布时间】:2015-06-22 10:27:26
【问题描述】:

我有来自服务器的这个 json 响应。

{"session_key":"thekey","expires_in":300,"environment":"exttest","country":"SE","private_feed":{"hostname":"priv.api.test.nordnet.se","port":443,"encrypted":true},"public_feed":{"hostname":"pub.api.test.nordnet.se","port":443,"encrypted":true}}

顶级信息被很好地解析到下面的类中。但是如何填充服务器信息列表?

代码

Response response = baseResource.path("login").queryParam("service", "NEXTAPI")
                .queryParam("auth", authParam).request(responseType).post(null);
        System.out.println(response);

        SessionInfo ses = response.readEntity(SessionInfo.class);

public class SessionInfo {
    public String session_key;
    public String environment;
    public int expires_in;
    public String country;

    List<ServerInfo> serverInfo = new ArrayList<ServerInfo>();
}

public class ServerInfo {
    public String hostname;
    public int port;
    public boolean encrypted;

}

这可行,但我希望有一种方法可以一步转换它,因为其他响应中可能有更多嵌套级别。

ObjectMapper mapper = new ObjectMapper();

        ObjectNode json = response.readEntity(ObjectNode.class);

        SessionInfo ses = mapper.treeToValue(json, SessionInfo.class); 
        ServerInfo s1 = mapper.treeToValue(json.get("private_feed"), ServerInfo.class);
        ServerInfo s2 = mapper.treeToValue(json.get("public_feed"), ServerInfo.class);
        ses.serverInfo.add(s1);
        ses.serverInfo.add(s2);

【问题讨论】:

  • 将您的响应转换为 JSON 并获取值
  • 当然可以手动解析。但是,当有这么好的功能可以读入课程时,如果可能的话,我想使用它。

标签: java json jersey


【解决方案1】:

我尝试使用 Jackson,并且能够在一个内衬中构建 JSON 对象。可能是您正在寻找的。​​p>

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;


public class JackSontest {

    public static void main(String[] args){
        String jstr = "{\"session_key\":\"thekey\",\"expires_in\":300,\"environment\":\"exttest\",\"country\":\"SE\",\"private_feed\":{\"hostname\":\"priv.api.test.nordnet.se\",\"port\":443,\"encrypted\":true},\"public_feed\":{\"hostname\":\"pub.api.test.nordnet.se\",\"port\":443,\"encrypted\":true}}";
    System.out.println("Calling jsonToObject...");
      ObjectMapper objectMapper = new ObjectMapper();
      try {

          SessionInfo info = objectMapper.readValue(jstr, SessionInfo.class);
       System.out.println("Session_key:- " + info.getSession_key());
      System.out.println("Expires_in:- " + info.getExpires_in());
      System.out.println("Environment:- " + info.getEnvironment());
      System.out.println("Private Feed:- " + info.getPrivate_feed().getHostname());
      System.out.println("Public Feed:- " + info.getPublic_feed().getHostname());

      } catch (JsonGenerationException e) {
       e.printStackTrace();
      } catch (JsonMappingException e) {
       e.printStackTrace();
      } catch (IOException e) {
       e.printStackTrace();
      }
    }
}

class SessionInfo {
    private String session_key;
    private String environment;
    private int expires_in;
    public String getSession_key() {
        return session_key;
    }
    public void setSession_key(String session_key) {
        this.session_key = session_key;
    }
    public String getEnvironment() {
        return environment;
    }
    public void setEnvironment(String environment) {
        this.environment = environment;
    }
    public int getExpires_in() {
        return expires_in;
    }
    public void setExpires_in(int expires_in) {
        this.expires_in = expires_in;
    }
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }

    private String country;


    private Feed private_feed;

    public Feed getPrivate_feed() {
        return private_feed;
    }

    @JsonProperty("private_feed")
    public void setPrivate_feed(Feed private_feed) {
        this.private_feed = private_feed;
    }

    private Feed public_feed;

    public Feed getPublic_feed() {
        return public_feed;
    }

    @JsonProperty("public_feed")
    public void setPublic_feed(Feed public_feed) {
        this.public_feed = private_feed;
    }
}

class Feed {
    private String hostname;
    private int port;
    private boolean encrypted;
    public String getHostname() {
        return hostname;
    }
    public void setHostname(String hostname) {
        this.hostname = hostname;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }
    public boolean isEncrypted() {
        return encrypted;
    }
    public void setEncrypted(boolean encrypted) {
        this.encrypted = encrypted;
    }

}

输出:

Calling jsonToObject...
Session_key:- thekey
Expires_in:- 300
Environment:- exttest
Private Feed:- priv.api.test.nordnet.se
Public Feed:- priv.api.test.nordnet.se

【讨论】:

  • 忽略了@JsonProperty("public_feed")
【解决方案2】:

你试过 Gson:

public class Employee
{
   private Integer id;
   private String firstName;
   private String lastName;
   private List<String> roles;
   private Department department; //Department reference

   //Other setters and getters
}

class DepartmentInstanceCreator implements InstanceCreator<Department> {
   public Department createInstance(Type type)
   {
      return new Department("None");
   }
}

//Now <strong>use the above InstanceCreator</strong> as below

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Department.class, new DepartmentInstanceCreator());
Gson gson = gsonBuilder.create();

System.out.println(
            gson.fromJson("{'id':1,'firstName':'Lokesh','lastName':'Gupta','roles':['ADMIN','MANAGER'],'department':{'deptName':'Finance'}}",
            Employee.class));

输出:

Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER], department=Department [deptName=Finance]]

source

【讨论】:

  • 是的,但是当您应该解析响应时,它确实倒退了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 2015-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多