赞
踩
给你一个形如下面的多层嵌套的JSON数据,你现在准备怎么put和get值其中的【content】字段的值呢?
- {
- "messages": [{
- "role": "user",
- "content": "生成快速排序算法"
- }],
- "model": "ziya-coding-34b",
- "max_tokens": 8192,
- "stream": true
- }
我可能会如下操作,有的朋友看了可能会笑,但我真的这么干过:
- public static void main(String[] args) {
- String jsonStr = "{\n" +
- " \"messages\": [{\n" +
- " \"role\": \"user\",\n" +
- " \"content\": \"生成快速排序算法\"\n" +
- " }],\n" +
- " \"model\": \"ziya-coding-34b\",\n" +
- " \"max_tokens\": 8192,\n" +
- " \"stream\": true\n" +
- "}";
- Map jsonMap = JSONUtil.toBean(jsonStr, Map.class);
- List list = (List)jsonMap.get("messages");
- Map o = (Map)list.get(0);
- String content = o.get("content").toString();
- System.out.println("content的值为:".concat(content));
- }
如果你还在这么干,别怕,Hutool会出手。在项目中引入依赖:
- <dependency>
- <groupId>cn.hutool</groupId>
- <artifactId>hutool-all</artifactId>
- <version>5.8.23</version>
- </dependency>
使用JsonObject对象的getByPath和setByPath方法,参数传入一个表达式。
"messages.0.content"
- [{
- "role": "user",
- "content": "生成快速排序算法"
- }],
- {
- "role": "user",
- "content": "生成快速排序算法"
- }
现在获取content的值只需要一行代码:
- String jsonStr = "{\n" +
- " \"messages\": [{\n" +
- " \"role\": \"user\",\n" +
- " \"content\": \"生成快速排序算法\"\n" +
- " }],\n" +
- " \"model\": \"ziya-coding-34b\",\n" +
- " \"max_tokens\": 8192,\n" +
- " \"stream\": true\n" +
- "}";
-
- JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
- String content = jsonObject.getByPath("messages.0.content").toString();
- String jsonStr = "{\n" +
- " \"messages\": [{\n" +
- " \"role\": \"user\",\n" +
- " \"content\": \"生成快速排序算法\"\n" +
- " }],\n" +
- " \"model\": \"ziya-coding-34b\",\n" +
- " \"max_tokens\": 8192,\n" +
- " \"stream\": true\n" +
- "}";
-
- JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
- jsonObject.putByPath("messages.0.content","新值");
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。