Json文件:
{
"policies": [
{
"planCode": "STR",
"planName": [
{
"language": "EN",
"description": "TravelSurance"
},
{
"language": "TC",
"description": "旅遊萬全保"
},
{
"language": "SC",
"description": "旅游万全保"
}
],
"involvedParties": [
{
"involvedPartyRole": [
"Owner"
],
"fullName": ""
}
],
"policyDetailsIndicator": true
}
]
}
代码:
package com.utils;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;
import net.minidev.json.parser.ParseException;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
public class FileParseJson {
private static Logger logger = LoggerFactory.getLogger(FileParseJson.class);
public static final String PROPERTY_FILE_PATH = "src/test/resources/UserProfiles/APIResponse.json";
public static JSONParser parser = new JSONParser();
Map<String, String> map = new HashMap<>();
@Test
public void readJsonFile() throws FileNotFoundException, ParseException {
Object obj = parser.parse(new FileReader(PROPERTY_FILE_PATH));
JSONObject jsonObject = (JSONObject) obj;
JSONArray policiesfields = (JSONArray) jsonObject.get("policies");
for(Object test : policiesfields){
JSONObject field = (JSONObject) test;
String planCodeValue = (String) field.get("planCode");
System.out.println("planCode :" + planCodeValue);
JSONArray planNameArray = (JSONArray) field.get("planName");
for(Object test1 : planNameArray){
JSONObject field1 = (JSONObject) test1;
String value = (String) field1.get("description");
map.put("description",value);
logger.info(map.toString());
}
}
}
}
运行结果:
planCode :STR
00:41:17.811 [main] INFO com.hsbc.dashboard.utils.FileParseJson - {description=TravelSurance}
00:41:17.811 [main] INFO com.hsbc.dashboard.utils.FileParseJson - {description=旅遊萬全保}
00:41:17.811 [main] INFO com.hsbc.dashboard.utils.FileParseJson - {description=旅游万全保}