zoukankan      html  css  js  c++  java
  • 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关键字

    顺利解决

  • 相关阅读:
    Openresty+redis实现灰度发布
    Nginx keepalived
    Nginx反向代理、负载均衡、动静分离、缓存、压缩、防盗链、跨域访问
    MYCAT扩容
    MYCAT全局序列
    MYCAT分库分表
    MySQL主从复制
    [redis] linux下集群篇(4) docker部署
    [nginx] CORS配置多域名
    [mysql] 归档工具pt-archiver,binlog格式由mixed变成row
  • 原文地址:https://www.cnblogs.com/tilv37/p/5753817.html
Copyright © 2011-2022 走看看