简体   繁体   English

如何在不解析为 Java 对象的情况下通过键获取动态 JSON 值?

[英]How to get dynamic JSON Value by Key without parsing to Java Object?

I am trying to get a json(has unknown template) value with a dynamic key like;我正在尝试使用动态键获取 json(具有未知模板)值;

"user.specs.id"

Problem is my json structure is not static and because of this I can't parse it to a java Object or get its properties with Gson methods.问题是我的 json 结构不是静态的,因此我无法将其解析为 java 对象或使用 Gson 方法获取其属性。

{
    "user": {
        "specs": {
            "id": 12222,
            "name": "foo"
        } 
    }
}

Is there a way to extract some data from any json with some key?有没有办法用某个键从任何 json 中提取一些数据?

EDIT: I have a service method like;编辑:我有一个服务方法;

public Object getValueByKey(String json, String key);

possible values for "json" param; “json”参数的可能值;

{"name": "test"}    //possible key "name"

{"user": {"id": 1232}}   //possible key "user.id"

{"cars": ["car1", "car2"]}   //possible key "cars[0]"

As @Michał Ziober's comment, you can simply achieve this by using JsonPath as follows: 正如@MichałZiober的评论一样,您可以使用JsonPath来实现此JsonPath ,如下所示:

Maven dependency Maven依赖

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

Code snippet 程式码片段

public static void main(String[] args) {
    getValueByKey("{\"name\": \"test\"}", "name");
    getValueByKey("{\"user\": {\"id\": 1232}}", "user.id");
    getValueByKey("{\"cars\": [\"car1\", \"car2\"]}", "cars[0]");
}

public static void getValueByKey(String json, String key) {
    DocumentContext jsonContext = JsonPath.parse(json);
    Object value = jsonContext.read(key);
    System.out.println(value.toString());
}

Console output 控制台输出

11:38:50.840 [main] DEBUG cjjinternal.path.CompiledPath - Evaluating path: $['name'] 11:38:50.840 [main]调试cjjinternal.path.CompiledPath-计算路径:$ ['name']
test 测试
11:38:50.855 [main] DEBUG cjjinternal.path.CompiledPath - Evaluating path: $['user']['id'] 11:38:50.855 [main]调试cjjinternal.path.CompiledPath-评估路径:$ ['user'] ['id']
1232 1232
11:38:50.855 [main] DEBUG cjjinternal.path.CompiledPath - Evaluating path: $['cars'][0] 11:38:50.855 [main]调试cjjinternal.path.CompiledPath-评估路径:$ ['cars'] [0]
car1 汽车1


Read more 阅读更多

I hope Property to json may help you you can refer For reference 希望json的Property可以帮助您参考

Java Properties to JSON From 5 version is not backward compatible! Java属性到JSON从5版本不向下兼容! The way creation of own json type resolvers has been changed! 自己的json类型解析器的创建方式已更改! But if you used only simple uses cases, migration (from 4.0) should pass without problems. 但是,如果仅使用简单的用例,则迁移(从4.0开始)应该顺利进行。

How to generate JSON from Java properties? 如何从Java属性生成JSON?

You can generate Json from: 您可以从以下位置生成Json:

from Java properties (java.util.Properties)
from Map<String,String> (import java.util.Map)
from Map<String,Object> (import java.util.Map)
from InputStream with properties (java.io.InputStream)
from File with properties (java.io.File)
from given localization of properties file

below variable "properties" as one of the above types: 下面的变量“属性”作为上述类型之一:

Maven dependency Maven依赖

 <dependency>
        <groupId>pl.jalokim.propertiestojson</groupId>
        <artifactId>java-properties-to-json</artifactId>
        <version>5.1.1</version>
    </dependency>

Simple Example code snippet: 简单的示例代码片段:

import pl.jalokim.propertiestojson.util.PropertiesToJsonConverter;

...
// properties as Map<String,String>, java.util.Properties, java.io.InputStream
String json = new PropertiesToJsonConverter().convertToJson(properties);

// convert from file
String jsonFromProperties = new PropertiesToJsonConverter().convertPropertiesFromFileToJson("/home/user/file.properties");
String jsonFromProperties2 = new PropertiesToJsonConverter().convertPropertiesFromFileToJson(new File("/home/user/file.properties"));

// for map with Object as value, String as key
Map<String,Object> valuesAsObjectMap = new HashMap<>();
String jsonFromProperties3 = new PropertiesToJsonConverter().convertFromValuesAsObjectMap(valuesAsObjectMap);

// converter Instance can be gathered through PropertiesToJsonConverterBuilder class, it has a few method for customization
PropertiesToJsonConverter propsToJsonConverter = PropertiesToJsonConverterBuilder.builder().build();

example properties: 示例属性:

object.man.name=John
object.man.surname=Doe
object.type=SOMETYPE
object.doubleNumber=1.2345
object.integerNumber=12
object.booleanValue1=true
object.booleanValue2=True
object.booleanValue3=false
object2.simpleArray[0]=value1
object2.simpleArray[1]=value2
object2.simpleArray[2]=value3
object2.simpleArray[3]=value4
object2.objectArray[0].field1=value1
object2.objectArray[0].field2=value2
object2.objectArray[0].field3=value3
object3.arrayWithDelimeter=value1,value2,value3
object3.simpleString=stringValue
object3.emptyValue=
object3.nullValue=null
multiDimArray[0][0]=00
multiDimArray[0][1]=01
multiDimArray[1][0]=10
multiDimArray[1][1]=11
objectFromText={"fieldName": "value"}
objectFromText.anotherField=anotherField_value

anotherMultiDimArray=[[12, true], [12, 123]] anotherMultiDimArray = [[12,true],[12,123]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 Java - JSON 解析中的 json 获取键值 - Get the key value from a json in Java - JSON Parsing 使用动态字符串值将动态 json 转换为 java object。 无键值json结构 - Convert dynamic json to java object with dynamic string value. No key value json structure 如何使用 java 替换动态 json object 中给定键路径的值 - How to replace a value of the given key path in dynamic json object using java 在Java中解析JSON-如何仅使用POJO从json文件属性(值-json对象)中获取String或JsonObject - Parsing JSON in java - how to get String or JsonObject from json file property(value - json object) using POJO only 使用动态键将json对象映射到java对象 - map json object with dynamic key to java object 如何使用正则表达式模式在不解析的情况下获取 JSON 属性值 - How to get JSON property value without parsing, using regex pattern 获取没有字符串键的Json值-Java JSONObject - get a Json value without string key - Java JSONObject 如何获取动态JSON数组中每个对象的密钥? - How do I get the key for each object in a dynamic JSON array? 根据 Java 中的键和值获取数组中的 json object - Get json object in Array based on key and value in Java Java Spring - 如何从非常嵌套的 json 中获取一个特定的键值而不映射到特定的 pojo? - Java Spring - How to get one specific key value from a very nested json without mapping to a specific pojo?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM