Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JSON value type need to be strictly defined? [duplicate]

Tags:

java

json

rest

gson

I have come across an API that returns different types of value for "fieldValue" as follow:

{
    "id" : 123,
    "fieldType" : "text",
    "fieldValue" : "some test"
}
{
    "id" : 456,
    "fieldType" : "checkbox",
    "fieldValue" : 
    [
        {
            "checkboxId" : 1,
            "name" : "Homer"
        },
        {
            "checkboxId" : 2, 
            "name" : "Marge"
        }
    ]
}
{
    "id" : 789,
    "fieldType" : "Select",
    "fieldValue" : {
        "selectId" : 3,
        "value" : "Lisa"
    }
}

I am using GSON and it doesn't like that the fact that "fieldValue" can be either String or an object or an array. I have written custom deserializer to parse it. My question is that does JSON specification allow JSON object to have loosely defined value type meaning fieldValue type can be either String, Array of objects or an object?

like image 986
StarDust Avatar asked Mar 25 '26 08:03

StarDust


2 Answers

The JSON specification only mentions the syntax of the JSON object, not the semantics. So the parser will not check if a given value should be of type A or B. It will read whatever values are available and will report errors if the syntax is broken. It is up to your application to verify the contents and react accordingly.

like image 165
HugoTeixeira Avatar answered Mar 27 '26 22:03

HugoTeixeira


No it does not even it sometimes might be a good policy. JSON specification itself does not tell what are the objects presented in JSON. That is in the responsibility of the API specification.

The API you have seems to rely on the discriminator field fieldType that I guess you are using to make your custom deserializing.

That is also the strategy that RuntimeTypeAdapterFactory uses which might be good solution also in your case.

like image 21
pirho Avatar answered Mar 27 '26 21:03

pirho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!