当前位置:   article > 正文

【Java / Hutool / JSON】多层嵌套的JSON数据,如何优雅地put和get?_hutool json.putbypath

hutool json.putbypath

1.示例JSON数据

给你一个形如下面的多层嵌套的JSON数据,你现在准备怎么put和get值其中的【content】字段的值呢?

  1. {
  2. "messages": [{
  3. "role": "user",
  4. "content": "生成快速排序算法"
  5. }],
  6. "model": "ziya-coding-34b",
  7. "max_tokens": 8192,
  8. "stream": true
  9. }

2.用Hutool之前以前


我可能会如下操作,有的朋友看了可能会笑,但我真的这么干过:

  1. public static void main(String[] args) {
  2. String jsonStr = "{\n" +
  3. " \"messages\": [{\n" +
  4. " \"role\": \"user\",\n" +
  5. " \"content\": \"生成快速排序算法\"\n" +
  6. " }],\n" +
  7. " \"model\": \"ziya-coding-34b\",\n" +
  8. " \"max_tokens\": 8192,\n" +
  9. " \"stream\": true\n" +
  10. "}";
  11. Map jsonMap = JSONUtil.toBean(jsonStr, Map.class);
  12. List list = (List)jsonMap.get("messages");
  13. Map o = (Map)list.get(0);
  14. String content = o.get("content").toString();
  15. System.out.println("content的值为:".concat(content));
  16. }

如果你还在这么干,别怕,Hutool会出手。在项目中引入依赖:

  1. <dependency>
  2. <groupId>cn.hutool</groupId>
  3. <artifactId>hutool-all</artifactId>
  4. <version>5.8.23</version>
  5. </dependency>

3.用Hutool之后

使用JsonObject对象的getByPathsetByPath方法,参数传入一个表达式。

表达式解释:

"messages.0.content"

  • messages:Map的key,该key对应的值是一个列表,获得的内容如下:
  1. [{
  2. "role": "user",
  3. "content": "生成快速排序算法"
  4. }],
  • 0:索引值,获取上一级列表对象的索引为0的元素,获得的内容如下:
  1. {
  2. "role": "user",
  3. "content": "生成快速排序算法"
  4. }
  • content:Map的key,获得目标key对应的值【生成快速排序算法】

现在获取content的值只需要一行代码:

①获取值:

  1. String jsonStr = "{\n" +
  2. " \"messages\": [{\n" +
  3. " \"role\": \"user\",\n" +
  4. " \"content\": \"生成快速排序算法\"\n" +
  5. " }],\n" +
  6. " \"model\": \"ziya-coding-34b\",\n" +
  7. " \"max_tokens\": 8192,\n" +
  8. " \"stream\": true\n" +
  9. "}";
  10. JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
  11. String content = jsonObject.getByPath("messages.0.content").toString();

②设置值:

  1. String jsonStr = "{\n" +
  2. " \"messages\": [{\n" +
  3. " \"role\": \"user\",\n" +
  4. " \"content\": \"生成快速排序算法\"\n" +
  5. " }],\n" +
  6. " \"model\": \"ziya-coding-34b\",\n" +
  7. " \"max_tokens\": 8192,\n" +
  8. " \"stream\": true\n" +
  9. "}";
  10. JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
  11. jsonObject.putByPath("messages.0.content","新值");
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/764955
推荐阅读
相关标签
  

闽ICP备14008679号