{
"log_id": 351445902943377670,
"words_result_num": 2,
"words_result": [{
"location": {
"width": 306,
"top": 0,
"left": 3,
"height": 83
},
"words": "单位:城市使浊"
}, {
"location": {
"width": 146,
"top": 41,
"left": 402,
"height": 35
},
"words": "8月7日"
}]
}
str字符串如上:
先从内到外建类。 如:Location 类 字段如下:
再建 一个Position 类字段如下
主要代码如下:
String str =
"{\"log_id\": 351445902943377670, \"words_result_num\": 21, \"words_result\": [{\"location\": {\"width\": 306, \"top\": 0, \"left\": 3, \"height\": 83}, \"words\": \"单位:城市使浊\"}, {\"location\": {\"width\": 146, \"top\": 41, \"left\": 402, \"height\": 35}, \"words\": \"8月7日\"}]}";
JSONObject jsonObject=JSONObject.fromObject(str);
//获得log_id
String log_id = jsonObject.getString("log_id");
//获得words_result_num
String words_result_num = jsonObject.getString("words_result_num");
// 获得words_result
JSONArray words_result = jsonObject.getJSONArray("words_result");
Image image = new Image();
List<Position> list = new ArrayList<Position>();
for(int i = 0 ;i < words_result.size();i++) {
//获得words
String words = words_result.getJSONObject(i).getString("words");
//获得locaton
JSONObject jo = words_result.getJSONObject(i).getJSONObject("location");
Position p = new Position();
Location location = new Location();
String top = jo.getString("top");
String left = jo.getString("left");
String width = jo.getString("width");
String height = jo.getString("height");
location.setTop(top);
location.setHeight(height);
location.setLeft(left);
location.setWidth(width);
p.setWords(words);
p.setLocation(location);
list.add(p);
}
image.setLog_id(log_id);
image.setWord_result(list);
image.setWords_result_num(words_result_num);
最后 的image 就是想要的对象,这个方法麻烦一些,但是每条语句都能知道是什么意思。我感觉好理解就是简单。
这个方法基本通用所有的复合类型对象。