zoukankan      html  css  js  c++  java
  • 使用XStream和MongoDB自己的jar工具实现or映射

    看了一下开源的工具,一般的实现方法是annotation的,需要对实体类进行注解,这里尝试不注解进行数据的保存和查找。
    首先需要将数据转换为json格式,可以使用xstream如下实现:
    public class JSONUtils {   
    private static XStream xs = new XStream(new JsonHierarchicalStreamDriver());
    //实体类的json字符串,需要重命名的情况
    public static String getJSONString(Object o,Map <String,Class<?>>map){

    for (Map.Entry<String, Class<?>> item : map.entrySet()) {
    xs.alias(item.getKey(), item.getValue());
    }
    return xs.toXML(o);
    }
    //实体类字符串的json字符串
    public static String getJSONString(Object o){       
    return xs.toXML(o);
    }
    }
    在mongo.jar中包括了JSON类可以实现json字符串和DBObeject之间的转换,就利用它来实现:
    实体类Product:
    class Product{
    String name;
    float price;
    String sku;
    Product(String n,float p,String s){
    name=n;
    price=p;
    sku=s;
    }
    public Product() {
    // TODO Auto-generated constructor stub
    }
    }
    然后关键代码如下:
    Mongo mongo=new Mongo("127.0.0.1", 27017);
    DB db=mongo.getDB("test");
    DBCollection coll=db.getCollection("products");
    //实体类对象
    Product product=new Product("益达", 12.3f, "dfdf");
    //参数的重命名,会影响到json字符串的键值
    Map<String,Class<?>>type=new HashMap<String, Class<?>>();
    type.put("product",Product.class);
    //转换为字符串
    System.out.println(JSONUtils.getJSONString(product,type));       
    //将字符串转换为DBObject
    DBObject dbo=(DBObject) JSON.parse(JSONUtils.getJSONString(product,type));
    System.out.println(dbo.toString());
    //coll.save(dbo);
    coll.insert(dbo);//保存数据
    //查询
    BasicDBObject target=(BasicDBObject) JSON.parse(JSONUtils.getJSONString(product,type));

    DBCursor dbc=coll.find(target);
    for (DBObject dbO : dbc) {
    System.out.println(dbO.toString()+"find-----");
    }
    System.out.println("over");

    }
  • 相关阅读:
    Ethical Hacking
    Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    Python Ethical Hacking
    食物链 POJ
    Wireless Network POJ
    Candies POJ
    畅通工程再续 HDU
    Jungle Roads HDU
  • 原文地址:https://www.cnblogs.com/macula7/p/1960388.html
Copyright © 2011-2022 走看看