Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define JSON Schema for Map<String, Integer>?

Tags:

I have a json :

{
"itemTypes": {"food":22,"electrical":2},
"itemCounts":{"NA":211}
}

Here the itemTypes and itemCounts will be common but not the values inside them (food, NA, electrical) which will be keep changing but the will be in the format : Map<String, Integer>

How do I define Json Schema for such generic structure ?

I tried :

"itemCounts":{
      "type": "object"
    "additionalProperties": {"string", "integer"}

    }
like image 908
Newbie Avatar asked Nov 22 '16 19:11

Newbie


People also ask

How do I specify a schema in a JSON file?

If you want to use a custom schema of your own that's part of your project, just click on your schema in Solution Explorer and then drag it to that dropdown list. Alternatively, you can use the $schema keyword in a JSON file to associate it with a schema.

How do I pass a JSON object to a map?

We need to use the JSON-lib library for serializing and de-serializing a Map in JSON format. Initially, we can create a POJO class and pass this instance as an argument to the put() method of Map class and finally add this map instance to the accumulateAll() method of JSONObject.

Can we have map in JSON?

We can convert a Map to JSON object using the toJSONString() method(static) of org. json. simple. JSONValue.

How does JSON store integers?

JSON does not have distinct types for integers and floating-point values. Therefore, the presence or absence of a decimal point is not enough to distinguish between integers and non-integers. For example, 1 and 1.0 are two ways to represent the same value in JSON.


2 Answers

You can:

{
  "type": "object",
  "properties": {
    "itemType": {"$ref": "#/definitions/mapInt"},
    "itemCount": {"$ref": "#/definitions/mapInt"}
  },
  "definitions": {
    "mapInt": {
      "type": "object",
      "additionalProperties": {"type": "integer"}
    }
  }
}
like image 158
esp Avatar answered Sep 19 '22 14:09

esp


The question is kind of badly described, let me see if I can rephrase it and also answer it.

Question: How to Represent a map in json schema like so Map<String, Something>

Answer:

It looks like you can use Additional Properties to express it https://json-schema.org/understanding-json-schema/reference/object.html#additional-properties

{
  "type": "object",
  "additionalProperties": { "type": "something" }
}

For example let's say you want a Map<string, string>

{
  "type": "object",
  "additionalProperties": { "type": "string" }
}

Or something more complex like a Map<string, SomeStruct>

{
  "type": "object",
  "additionalProperties": { 
    "type": "object",
    "properties": {
      "name": "stack overflow"
    }
  }
}
like image 43
franleplant Avatar answered Sep 21 '22 14:09

franleplant