Java JsonElement中的递归键搜索不返回值
我面临一个相对简单的递归函数的问题,我从中改编。该函数包括在嵌套的JsonElement(arg2)中搜索键(arg1),如果该键在输入中匹配,则返回其相应的值。最初的方法由一个void方法组成,该方法将值存储在一个静态列表中,但我需要更改该方法以返回一个字符串 我所面临的问题是,尽管算法在找到正确的键并返回其值时设法在JSON结构中递归搜索,但由于方法本身的递归调用,它实际上并没有退出该方法。此链接对此进行了说明:。因此,该方法总是返回一个“无值”字符串 我尝试了不同的策略来解决这个问题,但没有成功 我能请你帮我解决这个问题吗Java JsonElement中的递归键搜索不返回值,java,json,recursion,Java,Json,Recursion,我面临一个相对简单的递归函数的问题,我从中改编。该函数包括在嵌套的JsonElement(arg2)中搜索键(arg1),如果该键在输入中匹配,则返回其相应的值。最初的方法由一个void方法组成,该方法将值存储在一个静态列表中,但我需要更改该方法以返回一个字符串 我所面临的问题是,尽管算法在找到正确的键并返回其值时设法在JSON结构中递归搜索,但由于方法本身的递归调用,它实际上并没有退出该方法。此链接对此进行了说明:。因此,该方法总是返回一个“无值”字符串 我尝试了不同的策略来解决这个问题,但没
import java.util.Map;
import java.util.Set;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Utils {
public Utils() {}
public String searchJson(String key, JsonElement jsonElement) {
String value = "No value";
// If input is an array, iterate through each element
if (jsonElement.isJsonArray()) {
for (JsonElement jsonElement1 : jsonElement.getAsJsonArray()) {
searchJson(key, jsonElement1);
}
}
else {
// If input is object, iterate through the keys
if (jsonElement.isJsonObject()) {
Set<Map.Entry<String, JsonElement>> entrySet = jsonElement
.getAsJsonObject().entrySet();
for (Map.Entry<String, JsonElement> entry : entrySet) {
// If key corresponds to the
String key1 = entry.getKey();
if (key1.equals(key)) {
value = entry.getValue().toString();
return value;
}
// Use the entry as input, recursively
searchJson(key, entry.getValue());
}
}
// If input is element, check whether it corresponds to the key
else {
if (jsonElement.toString().equals(key)) {
value = jsonElement.toString();
return value;
}
}
}
return value;
}
public static void main(String[] args) {
Utils utils = new Utils();
// Create JSON response
String response = "{\"jsonData\":[{\"cards\":[{\"card\":\"MTE14019797\",\"Explanation\":{\"Message\":\"No explaination key identified\",\"Status\":\"Failed\"},\"Prediction\":{\"Confidence_intervals\":[{\"confidence\":\"0.614\",\"distance\":\"0.3\",\"range_lower\":\"1.117\",\"range_upper\":\"1.717\"}],\"Message\":\"\",\"Status\":\"Success\",\"point_estimate\":\"1.417\"}},{\"card\":\"MTE14019798\",\"Explanation\":{\"Message\":\"No explaination key identified\",\"Status\":\"Failed\"},\"Prediction\":{\"Confidence_intervals\":[{\"confidence\":\"0.584\",\"distance\":\"0.3\",\"range_lower\":\"1.852\",\"range_upper\":\"2.452\"}],\"Message\":\"\",\"Status\":\"Success\",\"point_estimate\":\"2.152\"}}],\"Status\":\"Success\",\"modelTarget\":\"MTEter\",\"modelType\":\"conformalRegression\",\"modelUpdated\":\"2020-09-01\",\"principalResults\":[\"point_estimate\",\"confidence\",\"distance\",\"modelUpdated\"]}]}\r\n";
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(response.toString()).getAsJsonObject();
System.out.println(json.toString());
System.out.println();
// Access card response
JsonArray cardResponse = json.get("jsonData").getAsJsonArray()
.get(0).getAsJsonObject()
.get("cards").getAsJsonArray();
// Iterate through individual responses
Iterator<JsonElement> cardIter = cardResponse.iterator();
while (cardIter.hasNext()) {
// Select next card
JsonObject card = cardIter.next().getAsJsonObject();
System.out.println(card);
String key = "Status";
// TODO: Replace with variable from map
// If selected card Id corresponds to that in the iterator,
// then search for the value associated to the selected end-point
String cardId = card.get("card").getAsString();
if (cardId.equals("MTE14019798")) {
String value = utils.searchJson(key, card);
System.out.print(value);
}
}
}
}```
import java.util.Map;
导入java.util.Set;
导入com.google.gson.JsonArray;
导入com.google.gson.JsonElement;
导入com.google.gson.JsonObject;
导入com.google.gson.JsonParser;
公共类UTIL{
公共Utils(){}
公共字符串searchJson(字符串键,JsonElement JsonElement){
String value=“无值”;
//如果输入是数组,则遍历每个元素
if(jsonElement.isJsonArray()){
对于(JsonElement jsonElement1:JsonElement.getAsJsonArray()){
searchJson(key,jsonElement1);
}
}
否则{
//如果输入是object,则遍历键
if(jsonElement.isJsonObject()){
Set entrySet=jsonElement
.getAsJsonObject().entrySet();
for(Map.Entry:entrySet){
//如果键对应于
字符串key1=entry.getKey();
如果(键1.等于(键)){
value=entry.getValue().toString();
返回值;
}
//以递归方式将条目用作输入
searchJson(key,entry.getValue());
}
}
//如果输入为元素,则检查它是否对应于键
否则{
if(jsonElement.toString().equals(key)){
value=jsonElement.toString();
返回值;
}
}
}
返回值;
}
公共静态void main(字符串[]args){
Utils Utils=新Utils();
//创建JSON响应
字符串响应=“{\'jsonData\”:[{\'cards\”:[{\'card\”:“MTE14019797\”,“解释\\”:“消息\\”:“未识别任何解释密钥”,“状态\\”:“失败\\”,“预测\\”:“{\'置信区间\\”:“0.614\”,“距离\\”:“0.3\”,“范围下限”:“1.117\,“范围上限”,“1\”,“状态\\”,“成功消息\\”“解释性”解释::““消息”解释:“:“消息”解释:“:“消息”消息:“:“非解释性非解释性关键点已被识别”,“现状”状态:“:“失败”1.417\\””:“1.417.7.7”点点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点:::,,,,,,,“1.1.1.1.1.1.1.1.1.1.1.7点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点估计点:“,,,,,,,,,“状态:“:::::::::::“1.1.1.1.1.1.1.1.1.1.1.1:\”2.152 \“}}],“状态\:”成功\“,”模型目标\“:”MTEter \“,”模型类型\“:”一致回归\“,”模型更新\“:”2020-09-01 \“,”原则结果\“:[”点估计\“,”置信度\“,”距离\“,”模型更新\“]}\r\n”;
JsonParser=新的JsonParser();
JsonObject json=parser.parse(response.toString()).getAsJsonObject();
System.out.println(json.toString());
System.out.println();
//访问卡响应
JsonArray cardResponse=json.get(“jsonData”).getAsJsonArray()
.get(0.getAsJsonObject())
.get(“卡片”).getAsJsonArray();
//反复查看各个响应
迭代器cardIter=cardResponse.Iterator();
while(cardIter.hasNext()){
//选择下一张卡
JsonObject card=cardIter.next().getAsJsonObject();
系统输出打印项次(卡片);
String key=“Status”;
//TODO:替换为映射中的变量
//如果选择的卡Id与迭代器中的卡Id相对应,
//然后搜索与选定端点关联的值
String cardd=card.get(“card”).getAsString();
如果(卡迪德等于(“MTE14019798”)){
String value=utils.searchJson(密钥、卡);
系统输出打印(值);
}
}
}
}```
如果在递归调用中没有返回值,则返回值会丢失。您可以将返回值保存在变量中并检查null,如果返回值不为null,则您已找到该值,并且可以从任何循环中断并从递归函数返回
我修改了一些部分,请检查一下。此外,在需要时添加空检查
class Utils {
public Utils() {
}
public String searchJson(String key, JsonElement jsonElement) {
String value = null;
// If input is an array, iterate through each element
if (jsonElement.isJsonArray()) {
for (JsonElement jsonElement1 : jsonElement.getAsJsonArray()) {
value = searchJson(key, jsonElement1);
if (value != null) {
return value;
}
}
} else {
// If input is object, iterate through the keys
if (jsonElement.isJsonObject()) {
Set<Map.Entry<String, JsonElement>> entrySet = jsonElement
.getAsJsonObject().entrySet();
for (Map.Entry<String, JsonElement> entry : entrySet) {
// If key corresponds to the
String key1 = entry.getKey();
if (key1.equals(key)) {
value = entry.getValue().toString();
return value;
}
// Use the entry as input, recursively
value = searchJson(key, entry.getValue());
if (value != null) {
return value;
}
}
}
// If input is element, check whether it corresponds to the key
else {
if (jsonElement.toString().equals(key)) {
value = jsonElement.toString();
return value;
}
}
}
return value;
}
}
class Main {
public static void main(String[] args) {
Utils utils = new Utils();
// Create JSON response
String response = "{\"jsonData\":[{\"cards\":[{\"card\":\"MTE14019797\",\"Explanation\":{\"Message\":\"No explaination key identified\",\"Status\":\"Failed\"},\"Prediction\":{\"Confidence_intervals\":[{\"confidence\":\"0.614\",\"distance\":\"0.3\",\"range_lower\":\"1.117\",\"range_upper\":\"1.717\"}],\"Message\":\"\",\"Status\":\"Success\",\"point_estimate\":\"1.417\"}},{\"card\":\"MTE14019798\",\"Explanation\":{\"Message\":\"No explaination key identified\",\"Status\":\"Failed\"},\"Prediction\":{\"Confidence_intervals\":[{\"confidence\":\"0.584\",\"distance\":\"0.3\",\"range_lower\":\"1.852\",\"range_upper\":\"2.452\"}],\"Message\":\"\",\"Status\":\"Success\",\"point_estimate\":\"2.152\"}}],\"Status\":\"Success\",\"modelTarget\":\"MTEter\",\"modelType\":\"conformalRegression\",\"modelUpdated\":\"2020-09-01\",\"principalResults\":[\"point_estimate\",\"confidence\",\"distance\",\"modelUpdated\"]}]}\r\n";
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(response.toString()).getAsJsonObject();
System.out.println(json.toString());
System.out.println();
// Access card response
JsonArray cardResponse = json.get("jsonData").getAsJsonArray()
.get(0).getAsJsonObject()
.get("cards").getAsJsonArray();
// Iterate through individual responses
Iterator<JsonElement> cardIter = cardResponse.iterator();
while (cardIter.hasNext()) {
// Select next card
JsonObject card = cardIter.next().getAsJsonObject();
System.out.println(card);
String key = "Status";
// TODO: Replace with variable from map
// If selected card Id corresponds to that in the iterator,
// then search for the value associated to the selected end-point
String cardId = card.get("card").getAsString();
if (cardId.equals("MTE14019798")) {
String value = utils.searchJson(key, card);
System.out.print(value);
}
}
}
}
类Utils{
公共公用事业(){
}
公共字符串searchJson(字符串键,JsonElement JsonElement){
字符串值=null;
//如果输入是数组,则遍历每个元素
if(jsonElement.isJsonArray()){
对于(JsonElement jsonElement1:JsonElement.getAsJsonArray()){
value=searchJson(键,jsonElement1);
if(值!=null){
返回值;
}
}
}否则{
//如果输入是object,则遍历键
if(jsonElement.isJsonObject()){
Set entrySet=jsonElement
.getAsJsonObject().entrySet();
for(Map.Entry:entrySet){
//如果键对应于