我正试图从while循环中提取一个值。在输出中,我可以捕获Else
语句中的值,但当它在控制台日志中时,我无法从主语句返回它。我希望能够返回";103〃;当我调用CCD_ 2函数时。
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.XML;
public class Tesst {
static String line = "", str = "";
public static void main(String[] args) throws Exception {
String filepath = "C:/Users/Navi/Downloads/sample.xml";
BufferedReader br = new BufferedReader(new FileReader(filepath));
while ((line = br.readLine()) != null) {
str += line;
}
br.close();
JSONObject jsondata = XML.toJSONObject(str);
System.out.println("From main: " + getValueFromKey(jsondata, "routing_bic"));
}
private static Integer getValueFromKey(JSONObject json, String key) {
boolean exists = json.has(key);
Iterator<?> keys;
String nextKeys;
Integer foundKey = 0;
if(!exists) {
keys = json.keys();
while (keys.hasNext()) {
// Store next Key in nextKeys
nextKeys = (String)keys.next();
try {
// Check if the given Key is a JSON Object
if(json.get(nextKeys) instanceof JSONObject) {
// If Key does not exist
if(!exists) {
// Recursive function call
getValueFromKey(json.getJSONObject(nextKeys), key);
}
} else if (json.get(nextKeys) instanceof JSONArray) {
JSONArray jsonArray = json.getJSONArray(nextKeys);
for(int i = 0; i < jsonArray.length(); i++) {
String jsonArrayString = jsonArray.get(i).toString();
JSONObject innerJsonObject = new JSONObject(jsonArrayString);
// Recursive function call
if(!exists) {
getValueFromKey(innerJsonObject.getJSONObject(nextKeys), key);
}
}
}
} catch (Exception e) {
System.out.println(e);
}
}
} else {
// If key exists, print value
foundKey += parseObject(json, key);
System.out.println("From loop: " + foundKey);
return foundKey;
}
// System.out.println("Found Key = " + foundKey);
return 1; // Return 1 when key not found
}
private static Integer parseObject(JSONObject json, String key) {
System.out.println("From parseObject = " + json.get(key));
return (Integer) json.get(key);
}
}
示例XML
<Test>
<BIBRq>
<UserId>123</UserId>
<CIFNo>123</CIFNo>
<CompanyId>asd</CompanyId>
<LegalId>123</LegalId>
<LegalIdType>ABC</LegalIdType>
<LegalIdCountry>ABC</LegalIdCountry>
</BIBRq>
<SubSvcRq>
<SubSvc>
<SubSvcRqHeader>
<SvcCode>ABCD</SvcCode>
<SubSvcSeq>1</SubSvcSeq>
<TxnRef>12345</TxnRef>
<ClientUserID/>
</SubSvcRqHeader>
<SubSvcRqDetail>
<ft_tnx_record>
<additional_field>
<account_details>
<routing_bic>103</routing_bic>
</account_details>
</additional_field>
</ft_tnx_record>
</SubSvcRqDetail>
</SubSvc>
</SubSvcRq>
</Test>
输出:
来自parseObject=103
来自环路:103
来自主:1
您的代码中有两个错误。
-
我注意到您递归地调用函数
getValueFromKey
。如果不为变量foundKey
分配递归调用的返回值,这将永远不会起作用
所以,只需更改以下中的每个递归调用:foundKey=getValueFromKey(…,key(;
-
此外,最后一条语句
return 1
是错误的,因为它将覆盖后续递归调用返回的任何可能值。因此,在替换中,您必须始终返回foundKey
变量
我稍微修改了您的代码,并用您的示例文件对其进行了测试,它运行良好。与您的不同,我还用try-with-resourcece块封装了BufferedReader
,我一直更喜欢它而不是简单的try-catch,因为它保证它会为您关闭流,即使在出现异常的情况下也是如此
这是代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.XML;
public class Test {
static String line = "", str = "";
public static void main(String[] args) throws Exception {
String filepath = "C:\Users\marco\Downloads\sample.xml";
try ( BufferedReader br = new BufferedReader(new FileReader(filepath)); ) {
while ((line = br.readLine()) != null) {
str += line;
}
}
JSONObject jsondata = XML.toJSONObject(str);
System.out.println("From main: " + getValueFromKey(jsondata, "routing_bic"));
}
private static Integer getValueFromKey(JSONObject json, String key) {
boolean exists = json.has(key);
Iterator<?> keys;
String nextKeys;
Integer foundKey = 0;
if(!exists) {
keys = json.keys();
while (keys.hasNext()) {
// Store next Key in nextKeys
nextKeys = (String)keys.next();
try {
// Check if the given Key is a JSON Object
if(json.get(nextKeys) instanceof JSONObject) {
// If Key does not exist
if(!exists) {
// Recursive function call
foundKey = getValueFromKey(json.getJSONObject(nextKeys), key);
}
} else if (json.get(nextKeys) instanceof JSONArray) {
JSONArray jsonArray = json.getJSONArray(nextKeys);
for(int i = 0; i < jsonArray.length(); i++) {
String jsonArrayString = jsonArray.get(i).toString();
JSONObject innerJsonObject = new JSONObject(jsonArrayString);
// Recursive function call
if(!exists) {
foundKey = getValueFromKey(innerJsonObject.getJSONObject(nextKeys), key);
}
}
}
} catch (Exception e) {
System.out.println(e);
}
}
} else {
// If key exists, print value
foundKey += parseObject(json, key);
System.out.println("From loop: " + foundKey);
}
// System.out.println("Found Key = " + foundKey);
return foundKey; // Return 1 when key not found
}
private static Integer parseObject(JSONObject json, String key) {
System.out.println("From parseObject = " + json.get(key));
return (Integer) json.get(key);
}
}
这是输出:
From parseObject = 103
From loop: 103
From main: 103