Java 中使用Jackson反序列化

Build.gradle:

compile group: 'org.codehaus.jackson', name: 'jackson-mapper-lgpl', version: '1.9.13'
compile group: 'org.codehaus.jackson', name: 'jackson-core-lgpl', version: '1.0.1'

compile group: 'httpunit', name: 'httpunit', version: '1.3'

分别引用jackson包和WebConversation/WebResponse等发送WebRequest相关的包。 点这个刷新来添加引用。

Main中调用请求

 String url ="http://****"; // Api的接口

        NormalService normalService; //NormalService是用来接收API的反序列化类
        normalService = (NormalService)test.CallResetAPI(Class.forName("NormalService"),url,"GET");

下面是CallResetAPI部分,是用了Java中的泛型,关于Java的泛型请参照http://www.cnblogs.com/iyangyuan/archive/2013/04/09/3011274.html

import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebResponse;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * Created by ygshen on 2015/3/3.
 */
public class test {
    public static <T> T CallResetAPI(Class<T> tClass, final String url, String method) throws Exception {

        WebConversation conversation = new WebConversation();
        WebResponse response = conversation.getResponse(url);
        String respStream = response.getText();
        return ReadObject(
                tClass,
                respStream);
    }


    private static <T> T ReadObject(
            Class<T> tClass,
            String stream) throws Exception {
        T data = tClass.newInstance();

        try {
            data = new ObjectMapper().readValue(stream,tClass);

        } catch (Exception e) {
            // Handle the problem
            throw e;
        }
        return data;
    }


}

下面是反序列化的类代码

import java.io.Serializable;
import java.util.List;

/**
 * Created by ygshen on 2015/3/3.
 */
public class NormalService implements Serializable
{
    public List<Service> serviceList;
    public int count;
    public String env;
    public Boolean success;
}


// Service部分代码

import java.io.Serializable;
import java.util.List;

/**
 * Created by ygshen on 2015/3/3.
 */

public class Service implements Serializable
{

    public String serviceCode;

    public String serviceName;
    public String serviceNamespace;
    public String serviceContacts;
    public List<ServiceEndpoint> endpointList;
}

/**
 * Created by ygshen on 2015/3/3.
 */
public class ServiceEndpoint {
    public String Test1;
    public String Test2;
    public String Test3;
}

  

这样只要测试Main函数中的输出就可以了。



原文地址:https://www.cnblogs.com/ygshen/p/4315678.html