使用Java从动态json查找键的值 [英] Find value for a key from a dynamic json using java
问题描述
我需要从动态json获取密钥的值.
输入-> json对象,字符串键
输出-> json元素(对应于键的值)
例子
I need to get the value of the key from a dynamic json.
Input-> json Object, String key
Output-> json element(corresponds to the value of the key)
Example
JsonObject Jmsg =
JsonObject Jmsg =
{
"id": "1753_CORE1",
"name": "Gtx cuda Service:1753",
"shortName": "gt-service-1753",
"createdDate": "Mar 31, 2015 4:47:10 PM",
"config": {
"oauthSecret": [
{
"id": 45,
"config123": {
"oauthSecret": "P8n2x5Hsst0nFRRB0A",
"status": "CREATED"
},
"SERVER132": "1000"
},
{
"id": 46,
"config123": {
"oauthSecret": "P8n2x5Htss0nFRRB0A"
},
"SERVER132": "1000"
}
],
"oauthKey": "154284-service-1753",
"SERVER": "1000"
},
"features": [
9004,
9005
]
}
和String键=状态";
然后JsonElement Jvalue = jsonGetValueformKey(Jmsg,key);
应该在JsonElement或字符串类型中返回"CREATED".
and String key = "status";
then
JsonElement Jvalue = jsonGetValueformKey(Jmsg,key);
should return 'CREATED' in JsonElement or string type.
如果字符串键=功能";
然后
JsonElement Jvalue = jsonGetValueformKey(Jmsg,key);
应该以JsonElement或jsonArray类型返回[9004,9005].
if String key = "features";
then
JsonElement Jvalue = jsonGetValueformKey(Jmsg,key);
should return [9004,9005] in JsonElement or jsonArray type.
如果未找到密钥,则返回null
JsonObject Jmsg可以是任何东西
if key not found then return null
JsonObject Jmsg can be anything
推荐答案
请尝试
package json;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class MyApp {
static List<String> list = new ArrayList<String>();
public static void main(String[] args) {
String key = "oauthSecret";
String json2 = "{\"config\": {\"oauthSecret\": [{\"id\": 45,\"config123\": {\"oauthSecret\": \"P8n2x5Ht0nFRRB0A\",\"status\": \"CREATED\"},\"SERVER132\": \"1000\"},{\"id\": 46,\"config123\": {\"oauthSecret\": \"wP8n2x5Ht0nFRRB0A\",\"status\": \"CREATED\"},\"SERVER132\": \"1000\"}],\"oauthKey\": \"newtest\",\"SERVER\": \"1000\"},\"features\": [ 9004, 9005] ,\"d\":\"dd\"}";
System.out.println("JSON: " + json2);
JsonParser p = new JsonParser();
check(key, p.parse(json2));
System.out.println("list size: " + list.size());
System.out.println(list);
}
private static void check(String key, JsonElement jsonElement) {
if (jsonElement.isJsonArray()) {
for (JsonElement jsonElement1 : jsonElement.getAsJsonArray()) {
check(key, jsonElement1);
}
} else {
if (jsonElement.isJsonObject()) {
Set<Map.Entry<String, JsonElement>> entrySet = jsonElement
.getAsJsonObject().entrySet();
for (Map.Entry<String, JsonElement> entry : entrySet) {
String key1 = entry.getKey();
if (key1.equals(key)) {
list.add(entry.getValue().toString());
}
check(key, entry.getValue());
}
} else {
if (jsonElement.toString().equals(key)) {
list.add(jsonElement.toString());
}
}
}
}
}
这篇关于使用Java从动态json查找键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!