json 里面 加一个json java 代码实现
时间: 2023-10-18 09:07:01 浏览: 34
以下是在Java中向JSON中添加一个JSON的示例代码:
```
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
// 创建一个JSON对象
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("name", "John");
jsonObject1.put("age", 25);
// 创建另一个JSON对象
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("id", 123);
jsonObject2.put("data", "some data");
// 将第二个JSON对象添加到第一个对象中
jsonObject1.put("extra_info", jsonObject2);
// 打印输出结果
System.out.println(jsonObject1.toString());
}
}
```
输出结果:
```
{"age":25,"extra_info":{"data":"some data","id":123},"name":"John"}
```
相关问题
json 里面 加一个json 怎么写
如果您想在一个 json 中添加另一个 json,可以使用如下的格式:
{
"key1": "value1",
"key2": {
"nested_key1": "nested_value1",
"nested_key2": "nested_value2"
}
}
其中,key2 对应的值是一个嵌套的 json。您可以在这个嵌套的 json 中添加更多的键值对。
json数组转list java代码实现
好的,以下是将 JSON 数组转为 List 的 Java 代码实现:
```
String jsonStr = "[\"apple\", \"banana\", \"orange\"]";
Type listType = new TypeToken<ArrayList<String>>(){}.getType();
List<String> fruitList = new Gson().fromJson(jsonStr, listType);
```
以上代码使用 Gson 库将 JSON 数组转换为 ArrayList 类型的 List。