将com.alibaba.fastjson.JSONObject扁平化
时间: 2023-09-12 21:05:54 浏览: 112
使用JSONObject解析json数据
可以使用递归的方式将一个嵌套的JSONObject对象扁平化成一个Map对象。
以下是一个示例代码:
```java
import com.alibaba.fastjson.JSONObject;
import java.util.*;
public class JSONFlattener {
public static Map<String, Object> flatten(JSONObject jsonObject) {
Map<String, Object> flattenedMap = new HashMap<>();
flatten("", jsonObject, flattenedMap);
return flattenedMap;
}
private static void flatten(String prefix, JSONObject jsonObject, Map<String, Object> flattenedMap) {
for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof JSONObject) {
flatten(prefix + key + ".", (JSONObject) value, flattenedMap);
} else {
flattenedMap.put(prefix + key, value);
}
}
}
}
```
使用示例:
```java
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John");
jsonObject.put("age", 30);
JSONObject address = new JSONObject();
address.put("street", "123 Main St");
address.put("city", "Anytown");
address.put("state", "CA");
jsonObject.put("address", address);
Map<String, Object> flattenedMap = JSONFlattener.flatten(jsonObject);
System.out.println(flattenedMap);
```
输出结果:
```
{name=John, age=30, address.street=123 Main St, address.city=Anytown, address.state=CA}
```
阅读全文