这是多少
JsonNode
响应具有不同的键值对,类似于下面的示例。我如何遍历它以获得键和值对的响应?
{
"message": "Results field contain api response",
"results": {
"Person 1": "USA",
"Person 2": "India",
"Name 3": "Europe",
"People": "Germany"
}
}
如果您可以假设基本结构,其中顶层是一个映射(JSONObject),其中包含带有简单值的“消息”键和带有键/值对集合值的“结果”键,那么这里是如何使用
JSON.simple
来读取结构:
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
class Test2 {
public static void main(String[] args) {
try (Reader reader = new FileReader("/tmp/test.json")) {
JSONObject root = (JSONObject)(new JSONParser()).parse(reader);
System.out.println("Message: " + root.get("message"));
JSONObject results = (JSONObject) root.get("results");
for (Object key: results.keySet())
System.out.println(key + ": " + results.get(key));
} catch (IOException | ParseException e) {
throw new RuntimeException(e);
}
}
}
结果:
Message: Results field contain api response
Person 1: USA
Person 2: India
People: Germany
Name 3: Europe
如果您无法假设特定的结构,那么您需要读取根并测试其类型。然后,如果它是 JSONObject,则迭代该对象中的键和值。然后,您必须测试迭代中每个值的类型,以了解如何处理该值。您将继续根据需要深入分析和处理结构中的所有值。如果您需要允许 JSONArray 值,您可以对这些值进行同样的操作,迭代数组中的值,对每个值重复该过程。等等等等。递归函数在这里效果很好,当您找到新的 JSONObject 或 JSONArray 值时,您可以调用与处理该子对象相同的函数。
这对我有用。 PersonInfo 类将包含人员和国家/地区的 getter 和 setter。
List<PersonInfo> listOfPersonInfos = new List<PersonInfo>();
result.get("results").fields().forEachRemaining(e -> {
PersonInfo personInfo = new PersonInfo();
personInfo.setCountry(e.getKey());
personInfo.setName(e.getValue().textValue());
listOfPersonInfos.add(personInfo);
});