gpt4 book ai didi

java - 将 Json 解析为 DBObject

转载 作者:可可西里 更新时间:2023-11-01 09:44:21 26 4
gpt4 key购买 nike

我有一个使用“test/plain”的 REST 服务,基本上我收到的字符串是一个 JSON 字符串,我有以下代码将 JSON 字符串解析为 DBObject,以便我可以将其保存到 MongoDB

@Timed
@POST
@Consumes("text/plain")
@Produces(MediaType.APPLICATION_JSON)
public Response insertscreenview(String message) {
// System.out.println(message);
final Logger logger = LoggerFactory.getLogger(ScreenviewResource.class);
logger.info("Screenview Insert Request Recieved" + "\n" + message);
screenviewInstance = new Screenview();
tracInfoInstance = new TracInfo();
BasicDBObject ageRangeId;
GeoCheckManager geoCheckInstance = new GeoCheckManager();
boolean brCheck;
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(message);

System.out.println(message);

DBObject objInstance = (DBObject)JSON.parse(message);
...}

我的 JSON 字符串如下所示

{
"Screenview": {
"TracInfo": null,
"Id": 0,
"ScreenName": "SettingsActivity",
"Timestamp": "2014-07-02T18:50:10",
"Timezone": "Asia/Kolkata",
"ApplicationId": null,
"DeviceId": null,
"UserId": null,
"SessionId": "5684ae84-9a48-49a5-ab47-fcb7de3c08cf"
},
"Session": {
"Id": "5684ae84-9a48-49a5-ab47-fcb7de3c08cf",
"StartTime": "2014-07-02T13:20:58",
"EndTime": "2014-07-02T13:21:09",
"EntryScreen": "AccessPointActivity",
"ExitScreen": "SettingsActivity",
"FirstEvent": "SCREEN STARTED",
"LastEvent": "SCREEN STOPPED",
"ApplicationId": "fa41f204bfc711e3b9f9c8cbb8c502c4",
"DeviceId": "0_6e505bcbe7e511e393b60aba4a7caa0b",
"UserId": "",
"TracInfoId": -1,
"SensorsInfo": null
},
"CustomParams": {
"Latitude": 0,
"Longitude": 0,
"Country": null,
"CountryCode": null,
"Region": null,
"RegionCode": null,
"City": null,
"Gender": null,
"Age": 0,
"Platform": "Android",
"OSVersion": "16",
"Manufacturer": "samsung",
"Resolution": "600 * 976",
"NetworkCarrier": null,
"Timezone": null
} }

它给我错误如下,我无法找到原因。

java.lang.ClassCastException: java.util.HashMap cannot be cast to com.mongodb.DBObject

最佳答案

您可以使用 BasicDBObject 而不是使用 DBObject,它有一个以 Map 作为输入的构造函数:

BasicDBObject obj= new BasicDBObject(JSON.parse(message));

或使用 ObjectMapper:

BasicDBObject obj = mapper.readValue(message, BasicDBObject.class);

关于java - 将 Json 解析为 DBObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24651053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com