简体   繁体   English

如何在JAVA中使用MongoDB而不为嵌套json多次编写代码段?

[英]How to use MongoDB in JAVA without writing code snippets multiple times for nested jsons?

What is the best way to use MongoDB in JAVA without writing code snippets multiple times for nested jsons? 在Java中使用MongoDB而不为嵌套json多次编写代码段的最佳方法是什么?

eg - for json - 例如-对于json-

{ abc : {xyz : {..}, xyz1 : {..}}, cvb : {..{..{..}},{..}}}

I don`t want to parse inner documents and just want to use it as I use in mongo shell without using ORM 我不想解析内部文档,只想像在mongo shell中使用的那样使用它而不使用ORM

You can use a Generic class shown below 您可以使用如下所示的通用类

//Declare a variable of returned type value
String brandname = "";
double equity = 0.0;

//Call Function value(DbObject,Nested_Path,variable)
while (tweet.hasNext()) {

                    DBObject t = tweet.next();
                    brandname = value(t, "brand", brandname);
                    equity = value(t, "bei.equity", equity);

}
//Generic Function
public static <T> T value(DBObject t, String header, T element) {

        if (header.contains(".")) {
            String children[] = header.split("\\.");
            int i = 1;
            DBObject temp = t;
            for (String child : children) {
                if (i == children.length) {
                    element = (T) temp.get(child);
                    return element;
                } else {
                    temp = (DBObject) temp.get(child);
                }
                i++;

            }
        } else {
            element = (T) t.get(header).toString();
            return element;
        }
        return null;

    }

For the new MongoDB API(3.0 onwards) use this - 对于新的MongoDB API(3.0及更高版本),请使用-

public static <T> T value(Document t, String header, T element) {

    if (header.contains(".")) {
        String children[] = header.split("\\.");
        int i = 1;
        Document temp = t;
        for (String child : children) {
            if (i == children.length) {
                element = (T) temp.get(child);
                return element;
            } else {
                temp = (Document) temp.get(child);
            }
            i++;

        }
    } else {
        element = (T) t.get(header).toString();
        return element;
    }
    return null;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM