使用Spring在MongoDB中存储JSON模式 [英] Storing a JSON schema in mongodb with spring

查看:1168
本文介绍了使用Spring在MongoDB中存储JSON模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring数据和mongodb的新手.我有一个表示JSON模式的JSON对象,我需要使用spring数据将其存储在mongodb中.但是JSON模式的问题在于JSON模式的结构是动态的.例如下面是两个结构完全不同的有效JSON模式.

I am new to Spring data and mongodb. I have a JSON object which represents a JSON Schema and I need to store that in mongodb using spring data. But the issue with JSON schema is the structure of JSON Schema is dynamic; for example below are two valid JSON schema with completely different structure.

{
    "type": "object",
    "properties": {
        "name": {
            "type": "string",
            "minLength": 10
        },
        "age": {
            "type": "integer"
        }
    },
    "required": [
        "name",
        "age"
    ]
}


{
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "abc": {
                "type": "boolean"
            },
            "xyz": {
                "$ref": "#/definitions/"
            },
            "asd": {
                "type": "null"
            }
        },
        "required": [
            "abc",
            "xyz"
        ]
    }
}

如何定义JAVA POJO类,以便可以将上述JSON与定义的类进行映射并将其存储在mongodb中.还是有可能在春季进行CURD操作而不将其映射到POJO类?

How can I define a JAVA POJO Class so that I can map the above JSON with the defined class and store it in mongodb. Or is it possible to do CURD operation in spring without mapping it to a POJO class?

推荐答案

我建议使用杰克逊.

Mongo模板具有CRUD方法,该方法采用集合名称和DBObject实体,这与直接使用mongo java驱动程序非常相似.

Mongo Template have CRUD methods which takes collection name and DBObject entity which is very similar to if you were to directly use mongo java driver.

因此,您将拥有json有效负载,并使用其中一个映射器库将其转换为Map.

So you will have json payload and using one of the mapper library to convert them into Map.

类似

反序列化

ObjectMapper mapper = new ObjectMapper(); 
TypeReference<HashMap<String,Object>> typeRef 
        = new TypeReference<HashMap<String,Object>>() {};
HashMap<String,Object> map = mapper.readValue(jsonpayload, typeRef); 

DBObject

DBObject dbObject = new BasicDBObject(map);

MongoTemplate

MongoTemplate

mongoTemplate.save(dbObject, "collectionname");

您可以对所有其他CRUD操作执行类似的操作.

You can do something similar for all other CRUD operations.

这篇关于使用Spring在MongoDB中存储JSON模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆