简体   繁体   English

在不知道格式的情况下解析JSON(可以是两个不同的对象之一)

[英]Parse JSON without knowing format (can be one of two different objects)

I have two concrete objects with a known schema (totally different). 我有两个具有已知架构的具体对象(完全不同)。 Then I get JSON from a client and want to map it into one of this object. 然后,我从客户端获取JSON,并希望将其映射到该对象之一。

Is it possible to somehow check type before conversion, or I have to try to convert it into each of object and check if parsing was correct? 是否可以在转换之前以某种方式检查类型,或者我必须尝试将其转换为每个对象并检查解析是否正确?

EDIT: In example: 编辑:例如:

{"id":"1","name":"oneone"}

and second 第二

{"age":50,"type":"elephant"}

Personally, I would parse the JSON using GSON or something similar and look for the key that is unique to one of the JSON formats, for instance "age". 就个人而言,我将使用GSON或类似方法解析JSON,然后寻找一种JSON格式所独有的密钥,例如“年龄”。 In reality, you could probably do this as a String as @user743414 mentioned as well. 实际上,您也可以像@ user743414一样将其作为String进行。

UPDATE: 更新:

Here is some code to reflect what I'm talking about 这是一些代码来反映我在说什么

JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = jsonParser.parse(jsonString).getAsJsonObject();
Set<String> keys = jsonObject.keySet();
if(keys.contains("age")){
    //Map to one object
} else {
    //Map to the other object
}

If you are sure schema is constant for both JSON's, then simply take a unique parameter like age in this example and check if it exists in the JSON. 如果确定两个JSON的模式都是恒定的,则只需在此示例中使用一个唯一的参数(例如age),然后检查它是否存在于JSON中。

If (String.contains(“age”)) {
  //then it’s 2nd JSON
} else {
  //then it’s 1st JSON
}

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

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