FastJson与Jackson对比

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mo_feng_/article/details/79248152

以前一直用FastJson,最近一个项目里,由于引入的第三方包里导过fastjson,如果再次引用会导致重包,很尴尬,我就用Jackson。
json字符串中,如果key的字母是大写,Jackson好像不能解析成功。Fastjson没问题。
下面是我的demo
maven中导包

<!--jackjson-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.3</version>
    </dependency>
    <!--fastjson-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.44</version>
    </dependency>

测试代码

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.IOException;

public class TestJson {

    private static final String json = "{\n" +
            "    \"ErrorCode\":{\n" +
            "        \"value\":\"0\",\n" +
            "        \"when\":\"1517384346\"\n" +
            "    },\n" +
            "    \"Switch_1\":{\n" +
            "        \"value\":\"1\",\n" +
            "        \"when\":\"1517646608\"\n" +
            "    },\n" +
            "    \"Switch_2\":{\n" +
            "        \"value\":\"0\",\n" +
            "        \"when\":\"1517646361\"\n" +
            "    },\n" +
            "    \"onlineState\":{\n" +
            "        \"value\":\"on\",\n" +
            "        \"when\":\"1517647637\"\n" +
            "    },\n" +
            "    \"uuid\":\"167C991BE35CFFF1DC615FABEB110BE1\"\n" +
            "}";

    @Test
    public void testJackJson() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        WallSwitchControl wallSwitchControl = (WallSwitchControl) jsonStringToBean(json, WallSwitchControl.class);
        System.out.println(objectMapper.writeValueAsString(wallSwitchControl));
    }

    @Test
    public void testFastJson() {
        WallSwitchControl wallSwitchControl = JSON.parseObject(json, WallSwitchControl.class);
        System.out.println(JSONObject.toJSONString(wallSwitchControl));
    }

    /**
     *  字符串转Bean
     * */
    public Object jsonStringToBean(String json, Class t) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            return objectMapper.readValue(json, t);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

Jackson解析不了大写字母的key。很尴尬

猜你喜欢

转载自blog.csdn.net/mo_feng_/article/details/79248152
今日推荐