现有weather.json文件,内容如下: [ {"temp":"20℃/30℃","weather":"晴转多云","city":"上海","pm":"2.5","wind":"1级"}, {"temp":"15℃/24℃","weather":"晴","city":"北京","pm":"3","wind":"3级"}, {"temp":"26℃/32℃","weather":"多云","city":"广州","pm":"4","wind":"2级"} ] ,请封装jsonParse方法解析Json数据。 public List<Weather> jsonParse(String json){ }
时间: 2023-06-08 14:06:52 浏览: 104
好的,您的问题已经记录下来了,我会根据您的要求进行回答。
关于您的问题,下面是封装jsonParse方法解析Json数据的代码:
```java
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Weather {
private String temp;
private String weather;
private String city;
private String pm;
private String wind;
public Weather(String temp, String weather, String city, String pm, String wind) {
this.temp = temp;
this.weather = weather;
this.city = city;
this.pm = pm;
this.wind = wind;
}
// getters and setters
public static List<Weather> jsonParse(String json) {
List<Weather> weatherList = new ArrayList<>();
JSONArray jsonArray = JSONArray.parseArray(json);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String temp = jsonObject.getString("temp");
String weather = jsonObject.getString("weather");
String city = jsonObject.getString("city");
String pm = jsonObject.getString("pm");
String wind = jsonObject.getString("wind");
Weather weatherObj = new Weather(temp, weather, city, pm, wind);
weatherList.add(weatherObj);
}
return weatherList;
}
}
```
这段代码中,我们使用了FastJson这个第三方库来解析Json数据。在jsonParse方法中,我们首先将Json字符串转化为JSONArray对象,然后遍历JSONArray的每一个元素,将JSONObject中对应的属性值赋值给对应的属性,最后将生成的Weather对象加入到List中,并返回List。
希望这个解答能够解决您的问题!
阅读全文