Anton
Anton

Reputation: 459

JSON Value in Java Object

I have JSON String (see below) and want to parse it into an Java object, that is basically not a problem. But as you can see the type of the value is not fix. Is there a way to parse this into objects with the fields

String key;
<JsonValue> value;
Timestamp time;

or something like this? It is important to me, to obtain the type of the value in a way that i can persist the data into a database.

[
    {
      "key": "someKey",
      "value": "SomeValue",
      "time": "2016-03-30 14:59:55.108"
    },
    {
      "key": "otherKey",
      "value": 42,
      "time": "2016-03-30 14:59:55.108"
    }
]

Upvotes: 1

Views: 379

Answers (3)

RZet
RZet

Reputation: 1074

What you’re trying to achieve seems to me a contradiction of basic JSON schema principles or schema validation in general.

If you were to define a schema representing your JSON documents, you would probably struggle to produce one due to ambiguity of the type corresponding to the “value” property.

If you want to preserve the ‘type’ of the value, I would suggest including it into your JSON document, e.g.

[
{
      "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"
}
]

The corresponding JSON schema would be:

{
  "$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"]
}

Note your database column also needs to be of a specific type hence string equivalent type for storing multiple data types is probably the best fit.

Upvotes: 0

An Do
An Do

Reputation: 309

Why not use generic type?

class JsonObj {
    String key; E value; Timestamp time;
}

And create concrete object based on your JSON.

Upvotes: 0

Matteo Baldi
Matteo Baldi

Reputation: 5828

String key;
Object value;
Timestamp time;

Then you can use instanceof (ex. value instanceof String) to identify the type.

Upvotes: 2

Related Questions