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


  线程“主”中的异常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列表传递给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;
}


}

最佳答案

您需要一一读取属性并将其设置在数据对象中。

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。

09-09 17:34