使用JSON.simple解析嵌套JSON数组,如何获取param3的参数值?
Parsing Nested JSON Array with JSON.simple
Hey there! You're already doing a solid job parsing the top-level parameters with JSON.simple—let's tackle that nested param3 array next.
Since param3 is another JSON array (just like your top-level example array), we can reuse the same iterator pattern you already have, just one level deeper. Here's how to implement it:
First, Update Your ExampleClass
Let's add a nested class or dedicated structure to hold the param3 values (adjust this to match your actual data model):
class ExampleClass { double param1; long param2; List<Param3Data> param3Items = new ArrayList<>(); // Nested class to store param3's inner values static class Param3Data { long param3_1; String param3_2; } }
Add the Parsing Logic for param3
Replace the ..... in your case "param3" block with this code:
case "param3": // Cast the value to JSONArray since param3 is an array JSONArray param3Array = (JSONArray) pair.getValue(); if (param3Array != null) { Iterator param3Iterator = param3Array.iterator(); while (param3Iterator.hasNext()) { ExampleClass.Param3Data param3Obj = new ExampleClass.Param3Data(); // Get the nested JSONObject from the array (JSON.simple maps objects to Map) Map param3Map = (Map) param3Iterator.next(); Iterator<Map.Entry> param3MapIterator = param3Map.entrySet().iterator(); // Iterate over the nested object's entries while (param3MapIterator.hasNext()) { Map.Entry param3Pair = param3MapIterator.next(); switch (param3Pair.getKey().toString()) { case "param3_1": param3Obj.param3_1 = (long) param3Pair.getValue(); break; case "param3_2": param3Obj.param3_2 = (String) param3Pair.getValue(); break; default: break; } } // Add the parsed param3 object to your ExampleClass list e.param3Items.add(param3Obj); } } break;
How This Works
- Cast to JSONArray: We first convert the
param3value from the parent object to aJSONArray(since it's wrapped in[]). - Iterate the Nested Array: We use an iterator to loop through each object inside
param3. - Parse the Inner JSONObject: Each element in the
param3array is a JSON object, which JSON.simple represents as a JavaMap. We iterate over this map's entries to extractparam3_1andparam3_2. - Store the Data: We populate the nested
Param3Dataclass and add it to the list in yourExampleClass.
This follows the exact same pattern you already used for the top-level example array—just applied one level deeper!
内容的提问来源于stack exchange,提问作者Mitch
相关产品推荐
相关产品推荐

