json String转换为Java Bean

时间:2015-12-03 09:21:02

标签: java json-lib

当我运行代码时,它会报告:

  

线程“main”中的异常java.lang.ClassCastException:   net.sf.json.JSONObject无法在.....

转换为ColorData

守则是:

public class JsonTest {

public static void main(String[] args) {


    ArrayList<ColorData> list = new ArrayList<>();

    ColorData data1 = new ColorData(1129, 0.35);
    ColorData data2 = new ColorData(1120, 0.39);

    list.add(data1);
    list.add(data2);

    Collections.sort(list);

    // Java list to json
    JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(list);

    // json to Java
    JSONArray jsonObject = JSONArray.fromObject(jsonArray);
    ArrayList<ColorData> resList = new ArrayList<ColorData>();

    for (int i = 0; i < jsonObject.size(); i++) {
        ColorData data = (ColorData) jsonObject.get(i);
        resList.add(data);
    }

}
}

在Java List to Json之后,它的toString是:

[{"HSV":1120,"denominator":1,"numerator":1,"quantity":0.39},{"HSV":1129,"denominator":1,"numerator":1,"quantity":0.35}]

然后将此字符串读回jsonObject,并将其解析为ColorData,并将其存储到resList中。

通过jsonObject.get(i)我可以获取{"HSV":1120,"denominator":1,"numerator":1,"quantity":0.39}等每个数据,但是如何将其转换为ColorData实例???

ColorData班级如下:

public class ColorData implements Comparable<ColorData>{

private int HSV;
private double quantity;

private int numerator = 1;
private int denominator = 1;


// init the value
public ColorData (int HSV, double quantity) {
    this.HSV = HSV;
    this.quantity = quantity;
}


// getter and setter
public int getHSV() {
    return HSV;
}
public void setHSV(int hSV) {
    HSV = hSV;
}
public double getQuantity() {
    return quantity;
}
public void setQuantity(double quantity) {
    this.quantity = quantity;
}
public int getNumerator() {
    return numerator;
}
public void setNumerator(int numerator) {
    this.numerator = numerator;
}
public int getDenominator() {
    return denominator;
}
public void setDenominator(int denominator) {
    this.denominator = denominator;
}

@Override
public int compareTo(ColorData o) {
   // TODO Auto-generated method stub
   if (this.quantity - o.quantity > 0)
    return -1;
   else if (this.quantity - o.quantity < 0)
    return 1;
   else
    return 0;
}


}

1 个答案:

答案 0 :(得分:0)

您需要逐个读取属性并将它们设置在数据对象中。

ColorData data;
for (int i = 0; i < jsonObject.size(); i++) {
        data = new ColorData();

        //{"HSV":1120,"denominator":1,"numerator":1,"quantity":0.39}
        data.setHSV(((JSONObject)jsonObject.get(i)).getInt("HSV"));
        data.setDenominator(((JSONObject)jsonObject.get(i)).getInt("denominator"));
        data.setNumerator(((JSONObject)jsonObject.get(i)).getInt("numerator"));
        data.setQuantity(((JSONObject)jsonObject.get(i)).getDouble("quantity"));

        resList.add(data);
    }

或者您可以使用GSON lib。