SpringBoot和MongoDB:POJO中JSONObject字段的保存问题

3

我有一个简单的POJO,类似于以下内容。出于简洁起见,省略了Getter和Setter。

@Document(collection = "posts")
public class Post {
    @Id
    public String id;
    
    @Field(name = "author")
    public String author;
    
    @Field(name = "title")
    public String title;
    
    @Field(name = "body")
    public JSONObject body;
    
    public Post() {

    }
    
    public Post(String id, String author, String title, JSONObject body) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.body = body;
    }

我使用MongoRepository的默认保存方式来保存数据:

import org.springframework.data.mongodb.repository.MongoRepository;

public interface PostRepository extends MongoRepository<Post, String> {

}

以下代码将数据保存到MongoDB中:

使用以下代码将数据保存到MongoDB中:

@PostMapping
    public Post addPost(HttpEntity<String> httpEntity) {
        try {
            JSONObject obj = new JSONObject(httpEntity.getBody());

            Post p1 = new Post("123", obj.getString("author"), obj.getString("title"), 
                    obj.getJSONObject("body"));

            return postRepository.save(p1);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Foo Not Found", e);
        }
    }

当它保存在MongoDB中时,它存储了一些原本不应该保存的JSON字段。

原始JSON:

{
   body: {
     blocks: {
        [
           { data: "Data 1", type: "Type 1" },
           { data: "Data 2", type: "Type 2" },
        ]
     },
     version: "1.2.2"
   }
}

保存的JSON:

{
   body: {
     map: {
        blocks: {
           myArrayList:
           [
               { map: { data: "Data 1", type: "Type 1" }, _class: "org.json.JSONObject" },
               { map: { data: "Data 2", type: "Type 2" }, _class: "org.json.JSONObject" },
           ],
           _class: "org.json.JSONArray"
        },
        version: "1.2.2"
     }
   }
}

当我尝试获取数据时,出现以下错误:
``` java.lang.IllegalStateException: 无法设置属性映射,因为没有 setter、wither,并且它不是持久化构造函数 public org.json.JSONObject() 的一部分! ```
这是我获取数据的方式:
@GetMapping(path = "/{id}")
    public Post getPost(@PathVariable String id) {
        try {
            Optional<Post> post = postRepository.findById(id);

            return post.orElseThrow();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Foo Not Found", e);
        }
    }

我的第一个问题是,是否有一种方法可以将JSON对象保存到MongoDB中,而不带有额外的字段(例如 map myArrayList )?

其次,我应该如何检索具有POJO中JSONObject字段的数据?

提前感谢!


你能解决这个问题吗? - jfk
2个回答

1
这是一个通用的解决方案,用于存储任何文档。
package io.innoit.elearning.generic;

import java.util.List;

import org.bson.Document;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/generic")
@CrossOrigin(origins = { "*" })
public class GenericController {

    @Autowired
    private MongoTemplate mongoTemplate;

    @PostMapping
    public ResponseEntity<Document> addData(@RequestBody String data) {
        JSONObject jsonObject = new JSONObject(data);
        String documentName = jsonObject.getString("documentName");
        Document doc = Document.parse(data);
        Document insertedDoc = mongoTemplate.insert(doc, documentName);
        return new ResponseEntity<>(insertedDoc, HttpStatus.CREATED);

    }

    @GetMapping("/{documentName}")
    public List<Document> getData(@PathVariable String documentName) {
        List<Document> allData = mongoTemplate.findAll(Document.class, documentName);
        return allData;
    }

}

0

您可以在POJO中使用BasicDBObject,并进行以下解析:

String json = "{
  "id": Mdt1,
  "user": "user",
  "metadata": {
"departament": "JUST",
"college":"informatics"
}
}";



BasicDBObject object = BasicDBObject.parse(json);

在setter中使用object


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接