How to ignore dynamic key when deserialising JSON with jackson - java

I am trying to access the data inside the X-Amz-Content-Sha256 parameter, but the X-Amz-Content-Sha256 key is different for each request so I cannot hardcode the key value.
Is there a way to access an object without knowing its key, when using mapper.readValue()?
"components": {
"parameters": {
"X-Amz-Content-Sha256": {
"name": "X-Amz-Content-Sha256",
"in": "header",
"schema": {
"type": "string"
},
}
}
}

You need to deserialize it to Map. Then you can check Map key to get desired values.
Sample code to deserialize JSON string to Map:
ObjectReader reader = new ObjectMapper().readerFor(Map.class);
Map<String, Object> jsonMap = reader.readValue(jsonString);

Related

Handling empty JSON

I need to send following JSON in API BODY POST request:
{
"name": "",
"type": "TEMP",
"shared": false,
"search": {
},
"order": [
]
}
In my MainBody.java, declared
private String name;
private String type;
private boolean shared;
private JSON search;
private Object order;
and defined getters and setters.
In Payload.java,
MainBody mb = new MainBody();
mb.setName("");
mb.setType("TEMP");
mb.setShared(false);
mb.setSearch(null);
mb.setOrder(new ArrayList<>());
ObjectMapper om = new ObjectMapper();
String myData = om.writerWithDefaultPrettyPrinter().writeValueAsString(mb);
System.out.println(myData);
results
{
"name" : "",
"type" : "TEMP",
"shared" : false,
"search" : null,
"order" : [ ]
}
Please assist with how search as { } can be achieved as per expected JSON instead of null.
TIA.
Instead of setting search to null, you need to set it to an empty object. I'm not sure which JSON library you are using, but there should be an object constructor like new JsonObject(). Depending on what the allowed values for search are, you may also want to consider representing it in your class as Map<String, String> or something like that.
I would try something like this:
mb.setSearch(new JSON());
This way you create empty object and there should be only {}. It also depends on which JSON library do you use.
Issue resolved after using JSONMapper.

Validate Map<String,Object> object matches json schema

I have a json schema, for example:
{
"type": "object",
"ignoreUnknown": true,
"properties": {
"address" : {
"type" : "string"
}
}
}
I want to check whether an object of type Map<String,Object> matches the schema or not.
The schema is received as a String.
How can I achieve this in Java? (Preferably using Jackson)
Thanks.
Although it isn't Jackson-based, you can do that using the everit-org/json-schema library as follows:
Map<String, Object> myInstance = ...
SchemaLoader.builder()
.schemaJson(new JSONObject("{my-schema-json}"))
.build().load().build().validate(new JSONObject(myInstance));
Disclaimer: I am a developer of this library

Deserializing Jackson object where key is value inside larger object

I have a rather large JSON object (this is a subset) I'm trying to parse:
{
"items": [
{
"Name": "Wallet",
"tags": [
"wallet",
"cardholder"
],
"features": {
"material": {
"location": "in-house"
},
"stitching": {
"location": "in-house"
}
},
"color": null,
"store": {
"address": "123 Main Street"
}
}
],
"jItem": 0
}
I have Java POJO's for all JSON objects except for the features object, which contains objects where the key is a dynamic value. My current only-POJO's code does this:
...
itemsJson = doGet(url);
ObjectMapper objMapper = new ObjectMapper();
Items items = objMapper.readValue(itemsJson, Items.class);
...
This gives me a hierarchy of Java POJO's representing my data. The one hitch is features. How can I parse the features data, with the keys as values, within this larger object? I've looked at other SO posts:
Deserialize JSON in Jackson where key is a value
Deserializing jackson dynamic key value
Jackson JSON key as value in Java
but none of these solutions have 1. an object where the key is the value and 2. an object where the key is the value is contained within an object. I do have parsing just the features working using this "just features JSON":
{
"features": {
"material": {
"location": "in-house"
},
"stitching": {
"location": "in-house"
}
}
}
with this code:
...
JsonNode jsonNodeRecord = objectMapper.readTree(App.class.getResourceAsStream("/data.json"));
List<JsonNode> recordNodes = jsonNodeRecord.findValues("features");
...
which gives me JsonNode's. This isn't ideal because I don't have my features data in a POJO.
The Question:
It's not clear to me how to integrate parsing the JSON using POJO's for everything except for features, with either the JsonNode code above or a custom deserializer as in the #1 SO link above.

declare java.util.Map into json-schema

I need to map a java.util.Map instance into a JSON-schema that is used by org.jsonschema2pojo maven plugin to create a POJO.
I didn't find a good and simple solution for this.
Could someone help me please?
This is my actual json-schema file
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Response",
"description": "A Response object",
"type": "object",
"properties": {
"result": {
"type": "string",
"description": "describes response status"
},
"msg": {
"type": "string",
"description": "user msgs"
}
},
"required": ["result"],
"additionalProperties": false
}
I need to add a field "errors" that is converted into a java.util.Map<String, String> in Java.
AFAIK additionalProperties does the job.
You can declare an errors property of type Map<String, Object> for example like this (this is yaml now):
...
properties:
errors:
type: object
additionalProperties:
type: object
You don't specify the type of the keys, since this describes a json document, which naturally has strings as keys on objects.
instead of type: object you can also do type: string for Map<String, String> or reference another definition if you have your own type as values in that map.

Searching JSon string using java

I am new To JSon and i want to search the following json string and get the required output.
String:
{"status":"Success","code":"200","message":"Retrieved Successfully","reason":null,"
"projects":
[
{
"projectName": "example",
"users":
[
{
"userName": "xyz",
"executions":
[
{
"status": "check",
"runs":
[
{
"Id": "------",
"Key": "---"
}
],
"RCount": 1
}
],
"RCount": 1
}
],
"RCount": 1
},
Like that i have many projects and now , if i give projectname and username as input i wantt to get its status as output.
Is it possible?If yes how?
You may use JSONObject for this.
JSONObject json = new JSONObject(string);
JSONArray[] projectsArray = json.getJSONArray("projects");
for(int i = 0; i < projectsArray.length; ++i)
{
String projectName = projectsArray[i].getString("projectName");
...
}
Use the same method to get the users.
You can use gson library. Using gson convert your json string to Map and then you can iterate through map to get required item
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> myMap = gson.fromJson(jsonString, type);
You can use the Google gson to map your json data structure to a Java POJOs.
Example :
You can have Projects class containing list/array of Users.
Users class containing list/array of Executions and so on.
Gson library can easily map the json to these classes as objects and you can access your data in a more elegant manner.
Here are a few references :
http://howtodoinjava.com/2014/06/17/google-gson-tutorial-convert-java-object-to-from-json/
http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

Categories

Resources