Java对象中的JSON值
我有JSON字符串(见下文),希望将其解析为Java对象,这基本上不是问题。但正如您所看到的,值的类型不是fix。有没有办法将其解析为带有字段的对象Java对象中的JSON值,java,json,parsing,types,Java,Json,Parsing,Types,我有JSON字符串(见下文),希望将其解析为Java对象,这基本上不是问题。但正如您所看到的,值的类型不是fix。有没有办法将其解析为带有字段的对象 String key; <JsonValue> value; Timestamp time; 然后可以使用instanceof(例如value instanceof String)来标识类型。为什么不使用泛型类型 class JsonObj { String key; E value; Timestamp time; } 并
String key;
<JsonValue> value;
Timestamp time;
然后可以使用instanceof(例如value instanceof String)来标识类型。为什么不使用泛型类型
class JsonObj {
String key; E value; Timestamp time;
}
并基于您的JSON创建具体对象。在我看来,您试图实现的目标与基本JSON模式原则或总体模式验证相矛盾。 如果要定义一个表示JSON文档的模式,由于“value”属性对应的类型不明确,可能很难生成一个模式 如果您想保留值的“类型”,我建议将其包含在JSON文档中,例如
[
{
"key": "someKey",
"value": "3.123",
"type": "number",
"time": "2016-03-30 14:59:55.108"
},
{
"key": "someKey",
"value": "someValue",
"type": "string",
"time": "2016-03-30 14:59:55.108"
}
]
对应的JSON模式为:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Some description",
"type" : "array",
"element" : {
"key" : {
"type" : "string"
},
"value" : {
"type" : "string"
},
"type" : {
"type" : "string"
},
"time" : {
"type" : "string"
}
},
"required": ["key", "value", "type", "time"]
}
注意:您的数据库列也需要为特定类型,因此用于存储多种数据类型的字符串等效类型可能是最合适的。为什么不将
值的值解析为对象
?您指的是Object类型的字段?喜欢对象值;?是的,这就是我的意思。看看杰克逊。这是一个很棒的JSON Java库。我考虑过这个解决方案,但我想将这个值保存到postgres数据库中。并且不想丢失类型信息——开始时包含的JSON值……嗯,表中的字段是如何定义的?它还没有固定,但我考虑过使用jsonWait类型的列,所以您希望将所有响应保存在一个字段中(实际上是免费的),并且您需要一个POJO来执行一些数据操作?如果要在数据库中存储整个JSON消息,为什么需要保留该类型?您可以在POJO中添加一个字符串来存储整个JSON…哦,现在我不想存储整个消息。。。我将有一个这样的表:keyColumn:text;valueColumn:Json;timeColumn:时间戳。
[
{
"key": "someKey",
"value": "3.123",
"type": "number",
"time": "2016-03-30 14:59:55.108"
},
{
"key": "someKey",
"value": "someValue",
"type": "string",
"time": "2016-03-30 14:59:55.108"
}
]
{
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Some description",
"type" : "array",
"element" : {
"key" : {
"type" : "string"
},
"value" : {
"type" : "string"
},
"type" : {
"type" : "string"
},
"time" : {
"type" : "string"
}
},
"required": ["key", "value", "type", "time"]
}