json工具类ObjectMapper的详细使用记录

1。用于json与其他对象之间转化的工具类:

public class JsonUtil {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    static {
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static <T> String toJsonStr(T o) {
        try {
            return MAPPER.writeValueAsString(o);//json转化为string
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    public static <T> T toJsonObject(String json, Class<T> valueType) {
        try {
            return MAPPER.<T>readValue(json, valueType);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }


    public static <T> List<T> toJsonListObject(String json, Class<T> valueType) {
        try {
            JavaType getCollectionType = MAPPER.getTypeFactory().constructParametricType(List.class, valueType);
            List<T> list = MAPPER.readValue(json, getCollectionType);
            return list;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    public static <T> T toJsonObject(InputStream stream, Class<T> valueType) {
        try {
            T object = MAPPER.<T>readValue(stream, valueType);
            return object;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }
}

将文件与对象关联的解析类:

public class JSON
{
    public static final String DEFAULT_FAIL = "\"Parse failed\"";
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
//.writerWithDefaultPrettyPrinter();用于输出时的格式化
    public static void marshal(File file, Object value) throws Exception
    {
        try
        {
            objectWriter.writeValue(file, value);
        }
        catch (JsonGenerationException e)
        {
            throw new Exception(e);
        }
        catch (JsonMappingException e)
        {
            throw new Exception(e);
        }
        catch (IOException e)
        {
            throw new Exception(e);
        }
    }

    public static void marshal(OutputStream os, Object value) throws Exception
    {
        try
        {
            objectWriter.writeValue(os, value);
        }
        catch (JsonGenerationException e)
        {
            throw new Exception(e);
        }
        catch (JsonMappingException e)
        {
            throw new Exception(e);
        }
        catch (IOException e)
        {
            throw new Exception(e);
        }
    }

    public static String marshal(Object value) throws Exception
    {
        try
        {
            return objectWriter.writeValueAsString(value);
        }
        catch (JsonGenerationException e)
        {
            throw new Exception(e);
        }
        catch (JsonMappingException e)
        {
            throw new Exception(e);
        }
        catch (IOException e)
        {
            throw new Exception(e);
        }
    }

    public static byte[] marshalBytes(Object value) throws Exception
    {
        try
        {
            return objectWriter.writeValueAsBytes(value);
        }
        catch (JsonGenerationException e)
        {
            throw new Exception(e);
        }
        catch (JsonMappingException e)
        {
            throw new Exception(e);
        }
        catch (IOException e)
        {
            throw new Exception(e);
        }
    }

    public static <T> T unmarshal(File file, Class<T> valueType) throws Exception
    {
        try
        {
            return objectMapper.readValue(file, valueType);
        }
        catch (JsonParseException e)
        {
            throw new Exception(e);
        }
        catch (JsonMappingException e)
        {
            throw new Exception(e);
        }
        catch (IOException e)
        {
            throw new Exception(e);
        }
    }

    public static <T> T unmarshal(InputStream is, Class<T> valueType) throws Exception
    {
        try
        {
            return objectMapper.readValue(is, valueType);
        }
        catch (JsonParseException e)
        {
            throw new Exception(e);
        }
        catch (JsonMappingException e)
        {
            throw new Exception(e);
        }
        catch (IOException e)
        {
            throw new Exception(e);
        }
    }

    public static <T> T unmarshal(String str, Class<T> valueType) throws Exception
    {
        try
        {
            return objectMapper.readValue(str, valueType);
        }
        catch (JsonParseException e)
        {
            throw new Exception(e);
        }
        catch (JsonMappingException e)
        {
            throw new Exception(e);
        }
        catch (IOException e)
        {
            throw new Exception(e);
        }
    }

    public static <T> T unmarshal(byte[] bytes, Class<T> valueType) throws Exception
    {
        try
        {
            if (bytes == null)
            {
                bytes = new byte[0];
            }
            return objectMapper.readValue(bytes, 0, bytes.length, valueType);
        }
        catch (JsonParseException e)
        {
            throw new Exception(e);
        }
        catch (JsonMappingException e)
        {
            throw new Exception(e);
        }
        catch (IOException e)
        {
            throw new Exception(e);
        }
    }
}

ObjectMapper 的一个使用例子:

final ObjectMapper mapper = new ObjectMapper(); // can use static singleton, inject: just make sure to reuse!
  MyValue value = new MyValue();
  // ... and configure
  File newState = new File("my-stuff.json");
  mapper.writeValue(newState, value); // writes JSON serialization of MyValue instance
  // or, read
  MyValue older = mapper.readValue(new File("my-older-stuff.json"), MyValue.class);

  // Or if you prefer JSON Tree representation:
  JsonNode root = mapper.readTree(newState);
  // and find values by, for example, using a JsonPointer expression:
  int age = root.at("/personal/age").getValueAsInt(); 

用ObjectMapper来输出一串json字符串:

import com.fasterxml.jackson.databind.ObjectMapper;
@Test
    public  void testJson() throws JsonProcessingException {
       List<Word>blogs= wordMapper.selectAll();
       String newjson = null;
       ObjectMapper objectMapper = new ObjectMapper();
      newjson= objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(blogs);
        System.out.println(newjson);
      newjson=  JsonUtil.toJsonStr(blogs.getClass());
        System.out.println(newjson.getBytes(StandardCharsets.UTF_8));
   
    }

结果:
在这里插入图片描述
把json串写入到文件中:

      List<Word>blogs= wordMapper.selectAll();
       String newjson = null;
       ObjectMapper objectMapper = new ObjectMapper();
        File newState = new File("my-stuff.json");
        objectMapper.writeValue(newState,blogs);

结果:
在这里插入图片描述
在这里插入图片描述
使用toJsonListObject得到json转化而来的对象:

  String newjson = "[{\"id\":1,\"english\":\"apple\",\"chinese\":\"苹果\",\"level\":1,\"frequency\":3,\"img\":\"http://localhost:8107/0.png\",\"usa\":\"an apple\"},\n" +
               "  {\"id\":2,\"english\":\"pear\",\"chinese\":\"梨子\",\"level\":2,\"frequency\":2,\"img\":\"http://localhost:8107/2.png\",\"usa\":\"eat pear\"},\n" +
               "  {\"id\":3,\"english\":\"car\",\"chinese\":\"车\",\"level\":1,\"frequency\":3,\"img\":null,\"usa\":\"cars(复数)buy car(买车)\"},{\"id\":4,\"english\":\"people\",\"chinese\":\"人\",\"level\":1,\"frequency\":3,\"img\":null,\"usa\":\"people(单复一样) we are people\"}]";




        List<Word>blog2= JsonUtil.toJsonListObject(newjson,Word.class);
        List<String>str = blog2.stream().map(e->{
            String ch = e.getChinese();
            return ch;
        }).collect(Collectors.toList());
        System.out.println(str);

输出
[苹果, 梨子, 车, 人]

一些相关注解:

@JsonInclude

//Include.Include.ALWAYS 默认
//Include.NON_DEFAULT 属性为默认值不序列化
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化
//Include.NON_NULL 属性为NULL 不序列化
@JsonProperty:用于指明属性的名称。
@JsonProperty(“create_date”)
private Date createDate;
此时将对象序列化以后得到的json串中上面的属性为create_date"
@JsonIgnore:用于忽略指定属性,当该注解出现在field、getter、setter或者构造方法中任意一个上时,都意味着忽略所有(即序列化和反序列化都被忽略);有一种情况,当getter上注解@JsonIgnore而setter上注解@JsonProperty,就会出现“只读”情况(read from input, but is not written output)。

@JsonIgnore

private String address;
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值