net.sf.json.JSONException: java.lang.NoSuchMethodException

在尝试将json对象转换为list时候出现了如下错误

Exception in thread "main" net.sf.json.JSONException: java.lang.NoSuchMethodException: AAA$Pdata.<init>()
    at net.sf.json.JSONObject.toBean(JSONObject.java:288)
    at net.sf.json.JSONArray.toCollection(JSONArray.java:444)
    at net.sf.json.JSONArray.toCollection(JSONArray.java:387)
    at AAA.main(SWDataCalculateFilter.java:149)
Caused by: java.lang.NoSuchMethodException: AAA$Pdata.<init>()
    at java.lang.Class.getConstructor0(Class.java:2730)
    at java.lang.Class.getDeclaredConstructor(Class.java:2004)
    at net.sf.json.util.NewBeanInstanceStrategy$DefaultNewBeanInstanceStrategy.newInstance(NewBeanInstanceStrategy.java:55)
    at net.sf.json.JSONObject.toBean(JSONObject.java:282)
    ... 3 more

代码如下

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class AAAAA extends BaseFilter{

    public static void main(String[] args){
        String json="[{"x":"0","y":"5"},{"x":"1","y":"6"},{"x":"2","y":0}]";
        JSONArray jsonarray = JSONArray.fromObject(json);
        System.out.println(jsonarray);
        List list = (List)JSONArray.toCollection(jsonarray, Pdata.class);
        System.out.println(2.1111>2.0010);
    }
    //坐标内部类
    public  class Pdata{
        public double getX() {
            return x;
        }

        public double getY() {
            return y;
        }

        public void setX(double x) {
            this.x = x;
        }

        public void setY(double y) {
            this.y = y;
        }

        private double x;
        private double y;
        public Pdata(){}
        public Pdata(double x,double y){
            this.x=x;
            this.y=y;
        }
    }

}

解决方案

1、对于目标转换类,需要添加一个参数为空的构造函数

2、对于内部类,需要加static关键字

顺利解决

原文地址:https://www.cnblogs.com/tilv37/p/5753817.html