java解析json中的所有属性并返回

本文介绍使用FastJSON库解析JSON数据的方法,通过递归遍历JSON对象和数组,提取所有属性名称。

java解析json中的所有属性并返回

使用的jar包为:fastjson-1.1.36.jar
判断是json对象还是json数组,json数组的话,获取第一个对象的属性即可,采用了递归的方式,详情代码如下。

/**
 * 解析json中的所有属性
 * @param json json值
 * @param father 父亲属性,初始为""或者null
 * @param result 返回数组
 */
public void eachProperties(Object json, String father, ArrayList<String> result) {
    String className = json.getClass().getSimpleName();
    if (className.equals("JSONObject")) {
        JSONObject jsonObj = (JSONObject) json;
        Iterator<String> iter = jsonObj.keySet().iterator();
        while (iter.hasNext()) {
            String nextIndex = iter.next();
            String prefix = father == null || father == "" ? nextIndex : father + "." + nextIndex;
            Object sonJson = jsonObj.get(nextIndex);
            eachProperties(sonJson, prefix, result);
        }
    } else if (className.equals("JSONArray")) {
        JSONArray array = (JSONArray) json;
        Object sonJson = array.get(0);
        eachProperties(sonJson, father, result);
    } else {
        String prefix = father;
        if (null != result) {
            result.add(prefix);
        }
    }
}
Java 中,可以使用 Jayway JsonPath 库来返回 JSON 中某个属性的路径。以下是具体的实现步骤和示例代码: 首先,需要添加 Jayway JsonPath 的依赖。如果使用 Maven,可以在 `pom.xml` 中添加以下依赖: ```xml <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>2.8.0</version> </dependency> ``` 以下是一个示例代码,展示了如何使用 JsonPath 来获取 JSON 中某个属性的路径: ```java import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; public class JsonPathAttributePathExample { public static void main(String[] args) { String json = "{\"store\":{\"book\":[{\"title\":\"Java指南\",\"price\":35},{\"title\":\"JSON解析\",\"price\":28}]}}"; DocumentContext ctx = JsonPath.parse(json); // 获取第一本书的标题属性的路径 String path = "$.store.book[0].title"; String title = ctx.read(path); System.out.println("属性路径: " + path + ", 属性值: " + title); } } ``` 在上述代码中,首先定义了一个 JSON 字符串,然后使用 `JsonPath.parse` 方法将其解析为 `DocumentContext` 对象。接着,指定了要获取属性的路径 `$.store.book[0].title`,使用 `read` 方法读取该属性的值。 如果要动态查找某个属性的路径,可以通过递归遍历 JSON 结构来实现。以下是一个简单的示例: ```java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.List; public class FindAttributePath { public static List<String> findAttributePath(JSONObject json, String targetKey) { List<String> paths = new ArrayList<>(); findPathRecursive(json, targetKey, "", paths); return paths; } private static void findPathRecursive(Object obj, String targetKey, String currentPath, List<String> paths) { if (obj instanceof JSONObject) { JSONObject jsonObject = (JSONObject) obj; for (String key : jsonObject.keySet()) { String newPath = currentPath.isEmpty() ? key : currentPath + "." + key; Object value = jsonObject.get(key); if (key.equals(targetKey)) { paths.add(newPath); } findPathRecursive(value, targetKey, newPath, paths); } } else if (obj instanceof JSONArray) { JSONArray jsonArray = (JSONArray) obj; for (int i = 0; i < jsonArray.size(); i++) { String newPath = currentPath + "[" + i + "]"; Object value = jsonArray.get(i); findPathRecursive(value, targetKey, newPath, paths); } } } public static void main(String[] args) { String jsonStr = "{\"store\":{\"book\":[{\"title\":\"Java指南\",\"price\":35},{\"title\":\"JSON解析\",\"price\":28}]}}"; JSONObject json = JSON.parseObject(jsonStr); List<String> paths = findAttributePath(json, "title"); for (String path : paths) { System.out.println("找到属性 'title' 的路径: " + path); } } } ``` 在这个示例中,定义了 `findAttributePath` 方法来查找指定属性的所有路径。该方法通过递归遍历 JSON 对象和数组,记录每个属性的路径,将匹配目标属性的路径添加到结果列表中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值