码迷,mamicode.com
首页 > 编程语言 > 详细

Java 中使用Jackson反序列化

时间:2015-03-05 14:28:13      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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函数中的输出就可以了。



Java 中使用Jackson反序列化

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!