使用jackson来进行数组格式的json字符串转换成List。

有一个字符串如下。如下,也是通过jackson把list转换成的json字符串,我想把它转过来,看网上的内容都不尽人如意,都是片断的内容。估计只有写的知道怎么使用,所以就直接看了jackson的官网,知道了使用方法。

用的类主要是

import org.codehaus.jackson.type.TypeReference;
import org.codehaus.jackson.map.ObjectMapper;

要转的字符串如下:

[{"id":"36CD0224C1ED25F5E0538A3B0B7A8190","catgId":null,"matcAmont":50000,"lendPoolId":"36CD0224C1C225F5E0538A3B0B7A8190","balance":50000,"matchFlag":1,"isLock":1,"createTime":1467576000000,"userId":0,"mltCustLendPool":{"id":"36CD0224C1C225F5E0538A3B0B7A8190","userId":157020,"state":1,"isLock":1,"balance":50000,"curTotaAmt":50000,"syncDate":1467561600000,"inviFlag":2,"investTime":1467595065000,"deadline":1499131065000,"billDate":1467681465000,"billDay":5,"productId":"6","productName":"xxx","investAmt":50000,"prodOrderId":38662,"userTelephone":"15922166933","userName":"张三","idcardNum":"1111111111111","projectNum":null,"matchModelCode":null,"creditProduct":{"id":"290AA19B1134838EE053A716C0769130","swldid":"6","prodName":"xxx","prodType":null,"prodRate":0.13,"synFeeRate":null,"payCapitalType":null,"freezeTime":12,"prodCode":6,"prodCatgory":1,"unit":1},"subject":null},"orderFlag":null,"subject":0,"projectNum":null,"matchModeCode":"1"},{"id":"36DA5B50E54E2790E0538A3B0B7A2261","catgId":null,"matcAmont":50000,"lendPoolId":"36CD0224C1C225F5E0538A3B0B7A8190","balance":50000,"matchFlag":1,"isLock":1,"createTime":1467748800000,"userId":0,"mltCustLendPool":{"id":"36CD0224C1C225F5E0538A3B0B7A8190","userId":157020,"state":1,"isLock":1,"balance":50000,"curTotaAmt":50000,"syncDate":1467561600000,"inviFlag":2,"investTime":1467595065000,"deadline":1499131065000,"billDate":1467681465000,"billDay":5,"productId":"6","productName":"xxx","investAmt":50000,"prodOrderId":38662,"userTelephone":"15922166933","userName":"王dd","idcardNum":"2222222222222","projectNum":null,"matchModelCode":null,"creditProduct":{"id":"290AA19B1134838EE053A716C0769130","swldid":"6","prodName":"dfdfd","prodType":null,"prodRate":0.13,"synFeeRate":null,"payCapitalType":null,"freezeTime":12,"prodCode":6,"prodCatgory":1,"unit":1},"subject":null},"orderFlag":null,"subject":0,"projectNum":null,"matchModeCode":"1"}]

主要代码如下:

        ObjectMapper mapper = new ObjectMapper();
        List<MltWaitLendReco> lendReco = mapper.readValue(listStr,new TypeReference<List<MltWaitLendReco>>() { });
        System.out.println(lendReco.get(0).getId());

这样就可以把json字符串转换成想要的List.

注意readValue()方法里的new TypeReference<List<MltWaitLendReco>>() { }写法很关键,你写成List.class是不行的,

还有一点,ObjectMapper类在com.fasterxml.jackson开头的包里也有,这里用的是org.codehaus.jackson

这里还有一个以前用的,对象和Json互转的工具类

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class JsonUtils {

    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);

    private final static ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        objectMapper.configure(JsonParser.Feature.INTERN_FIELD_NAMES, true);
        objectMapper.configure(JsonParser.Feature.CANONICALIZE_FIELD_NAMES, true);
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static String encode(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonGenerationException e) {
            logger.error("encode(Object)", e); //$NON-NLS-1$
        } catch (JsonMappingException e) {
            logger.error("encode(Object)", e); //$NON-NLS-1$
        } catch (IOException e) {
            logger.error("encode(Object)", e); //$NON-NLS-1$
        }
        return null;
    }

    /**
     * 将json string反序列化成对象
     *
     * @param json
     * @param valueType
     * @return
     */
    public static <T> T decode(String json, Class<T> valueType) {
        try {
            return objectMapper.readValue(json, valueType);
        } catch (JsonParseException e) {
            logger.error("decode(String, Class<T>)", e);
        } catch (JsonMappingException e) {
            logger.error("decode(String, Class<T>)", e);
        } catch (IOException e) {
            logger.error("decode(String, Class<T>)", e);
        }
        return null;
    }

    /**
     * 将json array反序列化为对象
     *
     * @param json
     * @param jsonTypeReference
     * @return
     */
    public static <T> T decode(String json, TypeReference<T> jsonTypeReference) {
        try {
            return (T) objectMapper.readValue(json, jsonTypeReference);
        } catch (JsonParseException e) {
            logger.error("decode(String, JsonTypeReference<T>)", e);
        } catch (JsonMappingException e) {
            logger.error("decode(String, JsonTypeReference<T>)", e);
        } catch (IOException e) {
            logger.error("decode(String, JsonTypeReference<T>)", e);
        }
        return null;
    }
}
时间: 2025-01-02 18:53:55

使用jackson来进行数组格式的json字符串转换成List。的相关文章

json字符串转换成json对象,json对象转换成字符串,值转换成字符串,字符串转成值

主要内容: 一.json相关概念 二.json字符串转换成json对象 (字符串-->JSON对象) 三.json对象转换成字符串(json对象-->字符串) 四.将值转换成字符串(值-->字符串) 五.字符串转成值(字符串-->值) 同步的交流学习社区:http://www.mwcxs.top/page/425.html 一.json相关概念 json,全称为javascript object notation,是一种轻量级的数据交互格式.采用完全独立于语言的文本格式,是一种理想

json字符串转换成json对象

Json字符与Json对象的相互转换方式有很多,接下来将为大家一一介绍下,感兴趣的朋友可以参考下哈,希望可以帮助到你 1>jQuery插件支持的转换方式: 代码如下: $.parseJSON( jsonstr ); //jQuery.parseJSON(jsonstr),可以将json字符串转换成json对象 2>浏览器支持的转换方式(Firefox,chrome,opera,safari,ie9,ie8)等浏览器: 代码如下: JSON.parse(jsonstr); //可以将json字符

json字符串转换成对象,对象转换成json字符串

方法一: 程序集:  System.Web.Extensions; 命名空间:System.Web.Script.Serialization; 最重要的类:JavaScriptSerializer //实例化 JavaScriptSerializer js = new JavaScriptSerializer(); js.Serialize();//将对象转换成json字符串:    序列号 js.Deserialize();//将json字符串转换成对象:  反序列化 方法二: 程序集:New

JSON字符串转换成Map对象

页面向后台action传递一个json字符串,需要将json字符串转换成Map对象 import java.util.HashMap; import java.util.Iterator; import java.util.Map; import net.sf.json.JSONObject; public Map<String, String> toMap(Object object) { Map<String, String> data = new HashMap<Str

C#中,JSON字符串转换成对象。

在前台提交(post)的数据中.除了强类型的数据外,还有一个额外的json数据提交 在这里我的办法是,在前台把json对象转换成字符串,然后提交. 测试demo 前台: @using(Html.BeginForm()) { <input type="text" id="json" name="json"/> <input type="submit" value="提交"/> } &l

IOS 把格式化的JSON字符串转换成字典

[html] view plaincopyprint? /*! * @brief 把格式化的JSON格式的字符串转换成字典 * @param jsonString JSON格式的字符串 * @return 返回字典 */ + (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString { if (jsonString == nil) { return nil; } NSData *jsonData = [jsonString d

c++ json字符串转换成map管理

在cocos2dx for lua中,我们经常通过lua的table传入c++使用,然后早c++层操作数据. 实现步骤大致如下: table->string->c++层->通过rapidjson解析->存放在map中管理 在lua中,转换table大致如下 local tbl = {} tbl["fang"] = 1 tbl["jian"] = 1.4 tbl["heng"] = true tbl["fjh&qu

【深入JAVA】将Json字符串转换成Map/List

在阅读的过程中有任何问题,欢迎一起交流 邮箱:[email protected] QQ:1494713801 Java代码 package jsonToMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import net.sf.json.JSONArray; import net.sf.json.JSONObject; /** * 说明 json字符串 转成 Map/List * @aut

Jackson将json字符串转换成泛型List

转:http://www.cnblogs.com/quanyongan/archive/2013/04/16/3024993.html Jackson,我感觉是在Java与Json之间相互转换的最快速的框架,当然Google的Gson也很不错,但是参照网上有人的性能测试,看起来还是Jackson比较快一点 Jackson处理一般的JavaBean和Json之间的转换只要使用ObjectMapper 对象的readValue和writeValueAsString两个方法就能实现.但是如果要转换复杂