将 含嵌套对象和数组的 JSON 字符串解析为 Map
小于 1 分钟
将 含嵌套对象和数组的 JSON 字符串解析为 Map
示例代码
@Test
public void JsonToComplexMap () {
// 示例的JSON字符串
String json = """
{
"person": {
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY"
},
"hobbies": ["reading", "swimming", "coding"]
}
}
""";
// 使用FastJSON2将JSON字符串转换为Map
Map<String, Object> map = JSON.parseObject(json, Map.class);
// 输出解析后的对象
System.out.println(map);
// 也可以访问具体的键值对
Map<String, Object> person = (Map<String, Object>) map.get("person");
System.out.println(person.get("name")); // 输出 John
System.out.println(person.get("age")); // 输出 30
// 访问嵌套的地址信息
Map<String, Object> address = (Map<String, Object>) person.get("address");
System.out.println(address.get("street")); // 输出 123 Main St
System.out.println(address.get("city")); // 输出 New York
System.out.println(address.get("state")); // 输出 NY
// 访问爱好列表
List<String> hobbies = (List<String>) person.get("hobbies");
System.out.println(hobbies); // 输出 [reading, swimming, coding]
}
输出
{person={"name":"John","age":30,"address":{"street":"123 Main St","city":"New York","state":"NY"},"hobbies":["reading","swimming","coding"]}}
John
30
123 Main St
New York
NY
["reading","swimming","coding"]