JSONPath和ObjectMapper的使用

JSONPath一般是对json串进行拆分,从json串中取部分值,ObjectMapper一般是从对整个json串做相应的转换操作

1.JSONPath的使用

原文地址:https://blog.csdn.net/liupeifeng3514/article/details/79180202

package com.example.activitydemo.entity;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.AfterDomainEventPublication;
import org.springframework.data.domain.DomainEvents;

import javax.persistence.*;
import java.util.Arrays;
import java.util.Collection;

@Data
@RequiredArgsConstructor
@NoArgsConstructor
public class TestPerson {

    private Integer id;

    private String city;

    private String name;

}

1.1 eval方法

        TestPerson testPerson=new TestPerson();
        testPerson.setCity("heBei");
        testPerson.setName("河北");
        String username = (String) JSONPath.eval(testPerson, "$.name");
        System.out.println(username);

输出:"河北"

1.2  read(String json, String path)

String json = "{\"store\":{\"book\":[{\"title\":\"高效Java\",\"price\":10},{\"title\":\"研磨设计模式\",\"price\":12},{\"title\":\"重构\",\"isbn\":\"553\",\"price\":8},{\"title\":\"虚拟机\",\"isbn\":\"395\",\"price\":22}],\"bicycle\":{\"color\":\"red\",\"price\":19}}}";
//获取json中store下book下的所有title
        List<Object> o= (List<Object>)JSONPath.read(json,"$.store.book.title");
        System.out.println(o);

输出:

["高效Java","研磨设计模式","重构","虚拟机"]
String json = "{\"store\":{\"book\":[{\"title\":\"高效Java\",\"price\":10},{\"title\":\"研磨设计模式\",\"price\":12},{\"title\":\"重构\",\"isbn\":\"553\",\"price\":8},{\"title\":\"虚拟机\",\"isbn\":\"395\",\"price\":22}],\"bicycle\":{\"color\":\"red\",\"price\":19,\"title\":\"价格\"}}}";
//获取json中store下所有的title的值
        List<Object> o2= (List<Object>)JSONPath.read(json,"$.store..title");
        System.out.println(o2);

输出:

[价格, 高效Java, 研磨设计模式, 重构, 虚拟机]

1.2.1 语法

[] : 做相关迭代操作,一般进行数组的迭代操作

?() :过滤操作,过滤出符合条件的信息

@ : 当前节点,现行节点
String json = "{\"store\":{\"book\":[{\"title\":\"高效Java\",\"price\":10},{\"title\":\"研磨设计模式\",\"price\":12},{\"title\":\"重构\",\"isbn\":\"553\",\"price\":8},{\"title\":\"虚拟机\",\"isbn\":\"395\",\"price\":22}],\"bicycle\":{\"color\":\"red\",\"price\":19,\"title\":\"价格\"}}}";
   
//筛选出json中store下的book下中包含isbn的所有值 
Object o3= JSONPath.read(json,"$.store.book[?(@.isbn)]");
System.out.println(o3);
String json = "{\"store\":{\"book\":[{\"title\":\"高效Java\",\"price\":10},{\"title\":\"研磨设计模式\",\"price\":12},{\"title\":\"重构\",\"isbn\":\"553\",\"price\":8},{\"title\":\"虚拟机\",\"isbn\":\"395\",\"price\":22}],\"bicycle\":{\"color\":\"red\",\"price\":19,\"title\":\"价格\"}}}";
        //筛选出json中store下book中price>10的所有信息
        Object o4=JSONPath.read(json,"$.store.book[?(@.price>10)]");
//获取json中store下book下title是"高效Java"的记录
Object o5=JSONPath.read(json,"$.store.book[?(@.title='高效Java')]");

语法:

JSONPath语义
$根对象
$[-1]最后元素
$[:-2]第1个至倒数第2个
$[1:]第2个之后所有元素
$[1,2,3]集合中1,2,3个元素
//数字在:之前则从0开始往后,数字在:之后若是负数则是从-1开始 ,-1表示最后一条
        //获取json中store下book中从开头至倒数第二条数据的所有值
        Object o6=JSONPath.read(json,"$.store.book[:-2]");
        //获取json中store下book中从第二条数据开始的所有值
        Object o7=JSONPath.read(json,"$.store.book[1:]");
//获取json中store下book数组的数量
        Object o8=JSONPath.read(json,"$.store.book.size()");

 

2. com.fasterxml.jackson.databind.ObjectMapper

public class ObjectMapperTest {
    public static ObjectMapper objectMapper=new ObjectMapper();
    static {
        //返回格式化后的json数据
        //如下
        //格式化前
//        {"id":3,"city":"廊坊","name":"河北"}
//      格式化后
//        {
//            "id" : 3,
//                "city" : "廊坊",
//                "name" : "河北"
//        }
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        //若json字符串中有新增字段并且在该字段在实体类中不存在,则不报错,默认是true
        //只是针对转换为单个实体类的情况,若是list则不论json中有无新增字段都不会报错
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        //定义事件转换的格式
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    }
    public static void main(String[] args) throws IOException {
        TestPerson testPerson=new TestPerson();
        testPerson.setName("河北");
        testPerson.setCity("廊坊");
        testPerson.setId(3);
        testPerson.setDate(new Date());

        //写入文件
        objectMapper.writeValue(new File("/work/rrr.txt"),testPerson);
        //对象转string字符串
        String str1=objectMapper.writeValueAsString(testPerson);
        System.out.println(str1);// {"id":3,"city":"廊坊","name":"河北"}

        //对象转为byte数组
        byte[] bytes=objectMapper.writeValueAsBytes(testPerson);
        System.out.println(bytes);

        //json字符串转java对象
        TestPerson testPerson1=objectMapper.readValue(str1,TestPerson.class);
        //json字符串数组转换为list数组,字符串转换为集合
        String aa="[{\"id\":3,\"city\":\"廊坊\",\"name\":\"河北\",\"type\":\"type\"}]";
        String bb="{\"id\":3,\"city\":\"廊坊\",\"name\":\"河北\",\"type\":\"type\"}";
        //type是json中新增字段,实体类中没有
        //json串转换为集合
        List<TestPerson> testPersons=objectMapper.readValue(aa, List.class);

        //集合转为字符串
        String str2=objectMapper.writeValueAsString(testPersons);
        System.out.println(str2);

        //byte数组转换为java对象
        TestPerson testPerson2=objectMapper.readValue(bytes,TestPerson.class);

        //Map转换为json串
        Map map=new HashMap();
        map.put("name","xiaoMing");
        map.put("city","liaoNing");
        map.put("id","36");
        String str3=objectMapper.writeValueAsString(map);
        System.out.println(str3);

        //json串转换为Map
        Map map1=objectMapper.readValue(str3,Map.class);
        System.out.println(map1);

    }


}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ObjectMapper是一个非常流行的Java库,用于将Java对象转换为JSON格式,以及将JSON格式转换为Java对象。下面是一个使用ObjectMapper的示例代码: ``` import com.fasterxml.jackson.databind.ObjectMapper; public class Example { public static void main(String[] args) { // Create an instance of ObjectMapper ObjectMapper objectMapper = new ObjectMapper(); // Convert a Java object to JSON MyObject myObject = new MyObject("John", 30); try { String json = objectMapper.writeValueAsString(myObject); System.out.println(json); } catch (JsonProcessingException e) { e.printStackTrace(); } // Convert JSON to a Java object String json = "{\"name\":\"John\",\"age\":30}"; try { MyObject myObject = objectMapper.readValue(json, MyObject.class); System.out.println(myObject.getName()); System.out.println(myObject.getAge()); } catch (JsonProcessingException e) { e.printStackTrace(); } } } class MyObject { private String name; private int age; public MyObject() {} public MyObject(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` 在上面的示例中,我们首先创建了一个ObjectMapper实例。然后,我们将一个Java对象转换为JSON字符串,使用writeValueAsString()方法。接着,我们将JSON字符串转换为Java对象,使用readValue()方法。注意,我们需要传入要转换的Java对象的类类型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值