有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从json数据创建java模型

我有一个json数据(我不能更改)存储在我的nosql Mongodb数据库中。 以下是数据的外观:

{"scans" : {
        "Bkav" : {
            "detected" : false,
            "version" : "1.3.0.4924",
            "result" : null,
            "update" : "20140214"
        },
        "MicroWorld" : {
            "detected" : false,
            "version" : "12.0.250.0",
            "result" : null,
            "update" : "20140216"
        },
        "nProtect" : {
            "detected" : false,
            "version" : "2014-02-16.01",
            "result" : null,
            "update" : "20140216"
        }
  }
}

我试图做的是基于spring boot创建一个rest Web服务,以便检索mongo中存储的数据,因此我需要设置我的模型(基于json格式),这就是我想到的:

public class Scans
{
    @Id
    private String id; 
    private Bkav Bkav;
    private NProtect nProtect;
    private MicroWorld-eScan MicroWorld-eScan;

    //getters and setters

    @Override
    public String toString()
    {
        return "ClassPojo [Bkav = "+Bkav+", nProtect = "+nProtect+", MicroWorld-eScan = "+MicroWorld-eScan+"]";
    }
 }

对于每个扫描仪(Bkav、nProtect、MicroWorld escan),我都有相同的型号:

public class "scanner" //that may be one of the above names;
{
    private String update;
    private String result;
    private String detected;
    private String version;
    //getters and setters
    @Override
    public String toString()
    {
        return "ClassPojo [update = "+update+", result = "+result+", detected = "+detected+", version = "+version+"]";
    }
}

既然我有比我在问题中列出的更多的扫描器,那么是否可以为所有扫描器只创建一个类呢


共 (1) 个答案

  1. # 1 楼答案

    首先,MicroWorld-eScan不是有效的类名或变量名

    根据我的经验,你需要这个模型

    public class Scans {
        @Id
        private transient String id; 
        private TreeMap<String, Scanner> scans;
    
        // for example
        public Bkav getBkav() {
            return map.get("Bkav");
        } 
    

    我建议使用不同的名称,以免与java.util.Scanner冲突