{[
{"adjustment":1654,
"adjustedDate":"2018-09-13",
"comment":"ForTesting",
"details[{"prodCode":"270001","prodType":"1","fromPercent":"0.4415","toPercent":"0.0000","prodName":"富","fundType":"3"},
{"prodCode":"0509","prodType":"1","fromPercent":"0.5585","toPercent":"0.0000","prodName":"币","fundType":"4"},
{"prodCode":"2750","prodType":"1","fromPercent":"0.0000","toPercent":"0.4000","prodName":"广发济","fundType":"3"},
{"prodCode":"1826","prodType":"1","fromPercent":"0.0000","toPercent":"0.6000","prodName":"国寿金币","fundType":"4"}]},
{"adjustment":1626,
"adjustedDate":"2018-02-01",
"comment":"懒牛智试1号",
"details[{"prodCode":"2701","prodType":"1","fromPercent":"0.0000","toPercent":"0.5000","prodName":"富","fundType":"3"},
{"prodCode":"0009","prodType":"1","fromPercent":"0.0000","toPercent":"0.5000","prodName":"币","fundType":"4"}
]}
我们来解析一下这个Json字符串。
首先, 最外层由一个大括弧”{}”包裹,那么我们对应的可以建一个实体类来对应,内部有两个元素,元素name比较明显是字符串类型的,元素students的值是由一个中括弧”[]”包裹,那么它对应的应该是一个数组或者列表。
接下来, 我们分析一下中括弧”[]”内部内容格式,中括弧内有三个大括弧包裹着的内容,并且内容格式基本相同,那么我们可以再定义一个实体类来对应这些大括弧。但是我们发现三个大括弧中的内容还是有些区别的,元素score对应的值虽然都是由一个大括弧来包裹,但是里边key的名称和数量都不相同。这样的情况我们不能很好的定义一个实体类来对应这个大括弧内的内容,不过我们可以定义一个Map来对应这个大括弧内的内容。
最终, 定义出来的实体类如下。
v_fund_adjust_history.Java
package models.yingmi.prod;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import play.db.jpa.GenericModel;
@Entity
public class v_fund_adjust_history extends GenericModel {
@Id
public String adjustment;
public String comment;
public String adjustedDate;
@OneToMany
public List details;
}
v_fund_adjust_detail.java
package models.yingmi.prod;
import javax.persistence.Entity;
import javax.persistence.Id;
import play.db.jpa.GenericModel;
//组合调仓详情
@Entity
public class v_fund_adjust_detail extends GenericModel {
@Id
public String prodCode;
public String prodName;
public String prodType ;
public Double fromPercent;
public Double toPercent;
public String fundType;
public Double getFromPercent() {
return fromPercent*100;
}
public Double getToPercent() {
return toPercent*100;
}
}
定义完之后,解析过程就非常简单了:
package com.test; import net.sf.json.JSONObject; import com.bean.Grades; public class Domain { public static void main(String[] args) { for (int i = 0; i < arr.size(); i++) { JSONObject json = JSONObject.fromObject(arr.get(i)); v_fund_adjust_history history = (v_fund_adjust_history) JSONObject.toBean(json, v_fund_adjust_history.class); JSONArray arrs = JSONArray.fromObject(history.details); history.details = (List
) JSONArray.toCollection(arrs, v_fund_adjust_detail.class); historys.add(history); } }
这个Json字符串有多层嵌套,还有不固定的元素。只要学会了方法,不管多少层也是能分析出来的。