1.用JSONObject类来解析json文件.
2.先导入依赖,具体如下:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
3.用一个json文件作为一个demo,我们来解析这个文件,名为RadarIF.json,具体格式如下.
{
"编号": "00001",
"位置": {
"经度": "23.6778",
"纬度": "50.6778",
"高度": "100.00"
},
"点值": [{
"值": "1000"
},
{
"值": "1100"
},
{
"值": "1200"
}
]
}
4.具体代码如下:
public class ReadJson {
public RadarIFMaterial getRadarIFMaterial(String file){
RadarIFMaterial radarIFMaterial = new RadarIFMaterial();
JSONObject data = JSONObject.parseObject(loadJson(file));
if (data.containsKey("编号")){
System.out.println("编号key值存在");
System.out.print("编号:");
String status = data.getString("编号");
System.out.println(status);
//往实体类里面set
radarIFMaterial.setIntelligenceId(status);
}else {
System.out.println("key值不存在");
}
if (data.containsKey("位置")){
System.out.println("位置key值存在");
JSONObject data1 = JSONObject.parseObject(data.getString("位置"));
if (data1.containsKey("经度")){
System.out.print("经度key值存在:");
System.out.println(data1.getDouble("经度"));
radarIFMaterial.setStationLongitude(data1.getDouble("经度"));
}else {
System.out.println("key值不存在");
}
if (data1.containsKey("纬度")){
System.out.print("纬度key值存在:");
System.out.println(data1.getDouble("纬度"));
radarIFMaterial.setStationLatitude(data1.getDouble("纬度"));
}else {
System.out.println("key值不存在");
}
if (data1.containsKey("高度")){
System.out.print("高度key值存在:");
System.out.println(data1.getDouble("高度"));
radarIFMaterial.setStationAltitude_m(data1.getDouble("高度"));
}else {
System.out.println("key值不存在");
}
}else {
System.out.println("key值不存在");
}
if (data.containsKey("点值")){
System.out.print("点值key值存在");
System.out.println(data.getJSONArray("点值"));
JSONArray j=data.getJSONArray("点值");
Integer[] arr = new Integer[j.size()];
for (int i = 0; i <j.size() ; i++) {
Object o=j.get(i);
JSONObject js=(JSONObject)o;
arr[i]=js.getInteger("值");
System.out.println("值为:"+js.getInteger("值"));
}
//实体的对象是个数组
radarIFMaterial.setFrequencyValue(arr);
}else {
System.out.println("key值不存在");
}
System.out.println(loadJson(file));
return radarIFMaterial;
}
public String loadJson (String file) {
StringBuilder json = new StringBuilder();
try {
URL urlObject = new URL("file:///" +file);
URLConnection uc = urlObject.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"UTF-8"));
String inputLine = null;
while ( (inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json.toString();
}
}
5.ParseOver
因篇幅问题不能全部显示,请点此查看更多更全内容