#XmlElement(name = "dummyAttrib")
#ApiModelProperty(value = "dummyAttrib")
JSONObject dummyAttrib = new JSONObject();
//setter and getter
Now., When I am accessing My Application in Swagger the dummy attribute looks like
"dummyAttrib": {
"values": "java.util.Collection<V>",
"empty": false,
"size": 0,
"entrySet": "Set[java.util.Map.java.util.Map$Entry<K, V>]",
"keySet": [
"K"
]
}
So While entering input for the dummyAttrib, it is bit difficult to delete the entire default stuff and add our own stuff.
Can any one please suggest me to hide the default data given by Swagger?
I want something like
"dummyAttrib":{}
So that I can add my stuff.
In your annotation, you can choose the dataType that you want to map to. So for example:
#XmlElement(name = "dummyAttrib")
#ApiModelProperty(value = "dummyAttrib", dataType = "java.lang.Object)
JSONObject dummyAttrib = new JSONObject();
Which will look like this:
{
"MyModel" : {
"type" : "object",
"properties" : {
"dummyAttrib" : {
"type" : "object",
"description" : "dummyAttrib"
}
}
}
}
Related
I am trying to send PUT request to the Zotero API, but I keep getting an error:
Caused by: org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: ['itemType' property not provided]
The JSON being sent is fine, so it is something with my code.
private void handleUpdateItemButton(ActionEvent event) throws IOException {
Properties props = restConnection.getAccessProperties();
ResponseEntity<JsonNode> res = restConnection.getRestTemplate().exchange(this.getItem(props, itemKey), new ParameterizedTypeReference<JsonNode>() {
});
if (res.getStatusCode() == HttpStatus.OK) {
JsonNode jsonNode = res.getBody();
printJSON(jsonNode);
JSONObject jsonObject = convertNodetoObject(jsonNode);
JSONObject jsonData = jsonObject.getJSONObject("data");
//jsonObject.getJSONObject("data").put("title", "This is the new title");
jsonData.put("title", "This is the new title");
ResponseEntity<JsonNode> updatedItem = restConnection.getRestTemplate().exchange(this.updateItem(props, jsonData, itemKey), new ParameterizedTypeReference<JsonNode>() {
});
}
else{
System.out.println("This item cannot be updated");
}
}
The method above then calls the method below
private RequestEntity updateItem(Properties props, JSONObject item, String itemKey) throws JsonProcessingException {
ResponseEntity<JsonNode> res = restConnection.getRestTemplate().exchange(this.getItem(props, itemKey), new ParameterizedTypeReference<JsonNode>() {
});
return RequestEntity
.put(restConnection.getZoteroBaseURL() + "/users/" + props.getProperty("username") + "/items/" + itemKey)
.header("Zotero-API-Version", "3")
.header("Zotero-API-Key", props.getProperty("key"))
.header("If-Unmodified-Since-Version", numberBody.get("version").toString())
.header("Content-Type", "application/json")
.body(item);
}
Not really sure what is wrong. I'd appreciate any help - zoter-dev said that the PUT request should work and it's something with my code. Thanks!
I'd suggest you take a good look at the Zotero Web API documentation.
If you examine the creating an item section you'll find what you need to pass in your API call in order for it to work:
[
{
"itemType" : "book",
"title" : "My Book",
"creators" : [
{
"creatorType":"author",
"firstName" : "Sam",
"lastName" : "McAuthor"
},
{
"creatorType":"editor",
"name" : "John T. Singlefield"
}
],
"tags" : [
{ "tag" : "awesome" },
{ "tag" : "rad", "type" : 1 }
],
"collections" : [
"BCDE3456", "CDEF4567"
],
"relations" : {
"owl:sameAs" : "http://zotero.org/groups/1/items/JKLM6543",
"dc:relation" : "http://zotero.org/groups/1/items/PQRS6789",
"dc:replaces" : "http://zotero.org/users/1/items/BCDE5432"
}
}
]
It's stated that All properties other than itemType, tags, collections, and relations are optional, meaning itemType is mandatory.
You must fill in these four properties, at least, if you want your call to succeed.
If you don't have any data for tags, collections or relations you could just pass empty property values:
{
"itemType" : "note",
"note" : "My sample note",
"tags" : [],
"collections" : [],
"relations" : {}
}
At present I am pulling my folder structure data as mentioned below.
{
{
"parent": "TestParent1"
"Child" : "TestSub1"
"GrnadChild":"TestGrandChild1"
},
{
"parent": "TestParent1"
"Child" : "TestSub1"
"GrnadChild":"TestGrandChild2"
},
{
"parent": "TestParent1"
"Child" : "TestSub2"
"GrnadChild":"TestGrandChild3"
},
{
"parent": "TestParent1"
"Child" : "TestSub2"
"GrnadChild":"TestGrandChild4"
}
}
I have a parent folder that consists 2 sub folder and each sub folder consists 2 grand folders.
I need the data to be framed in below json format.
{
"parent": "TestParent1",
{
"Child" : "TestSub1"
{
"GrnadChild" :
{
"TestGrandChild1",
"TestGrandChild2"
}
},
"Child" : "TestSub2"
{
"GrnadChild" :
{
"TestGrandChild3",
"TestGrandChild4"
}
}
},
"parent": "TestParent2",
{
"Child" : "TestSub3"
{
"GrnadChild" :
{
"TestGrandChild5",
"TestGrandChild6"
}
},
"Child" : "TestSub4"
{
"GrnadChild" :
{
"TestGrandChild7",
"TestGrandChild8"
}
}
}
}
Kindly assist me to wirte the java logic and Appreciate your help.
Serialize JSON to Object
String json;
FolderStruc original = new ObjectMapper()
.readerFor(FolderStruc.class)
.readValue(json);
Convert to Desired Object Model
DesiredStruc desired = new DesiredStruc(original);
De-serialize Object to JSON
String json = new ObjectMapper().writeValueAsString(desired);
If you are having any issues with correctly mapping your model to the desired output, try these annotations:
https://www.baeldung.com/jackson-annotations
Here is a code for implementation. You have to add json-simple jar to your library
JSONArray grandchild = new JSONArray();
JSONArray child = new JSONArray();
JSONArray parent = new JSONArray();
grandchild.add("GC1");
grandchild.add("GC1");
child.add("C1");
JSONObject obj = new JSONObject();
obj.put("GC", grandchild);
child.add(obj);
parent.add("P");
obj = new JSONObject();
obj.put("C", child);
parent.add(obj);
System.out.println(parent);
Output generated will look like :
["P",{"C":["C1",{"GC":["GC1","GC1"]}]}]
According to the Structuring a complex schema, it's possible to have the following relation:
Base JSON Schema (customer.json)
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"billing_address": { "$ref": "address.json" }
}
}
Referenced JSON Schema (address.json)
{
"type": "object",
"properties": {
"street_address": { "type": "string" },
"city": { "type": "string" },
"state": { "type": "string" }
},
"required": ["street_address", "city", "state"]
}
The key advantage of such an approach is reusability.
The issue appears if I want to compose these schemas into one. For example, I need to generate a JSON file with dummy values for all supported fields.
So, I want to have this schema as a result:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"billing_address": {
"street_address": { "type": "string" },
"city": { "type": "string" },
"state": { "type": "string" }
}
}
}
Note that all schemas are present in the classpath.
I've been searching for existing solutions on how to do it in Java.
Unfortunately, most of the libraries solve the tasks of how to generate schema by POJO. But in this case, I need the reverse one
There are generators in both directions:
from POJO to Schema
from Schema to POJO
You seem to be interested in neither since what you want is:
from Schema (parts) to (single) Schema
I'm afraid your chances of finding an existing solution may be small.
But you should be able to do this yourself, especially if you can make a couple of simplifying assumptions:
Nowhere in your data model do you have properties with the name $ref.
All your schema parts are present on the classpath – for simplicity's sake: in the same package as the java class performing
the merge of the separate schema part.
There is no circular reference to your main/entry schema from one of its referenced other schema parts.
It is acceptable to include the different parts in the entry schema's definitions.
The schema parts do not have overlapping definitions.
The utility could look something like this then:
public class SchemaMerger {
private final ObjectMapper objectMapper = new ObjectMapper();
private final Map<String, ObjectNode> schemas = new HashMap<>();
private final List<ObjectNode> definitions = new ArrayList<>();
public String createConsolidatedSchema(String entrySchemaPath) throws IOException {
ObjectNode entrySchema = this.getSchemaWithResolvedParts(entrySchemaPath);
ObjectNode consolidatedSchema = this.objectMapper.createObjectNode().setAll(entrySchema);
ObjectNode definitionsNode = consolidatedSchema.with("definitions");
this.definitions.forEach(definitionsNode::setAll);
for (Map.Entry<String, ObjectNode> schemaPart : this.schemas.entrySet()) {
// include schema loaded from separate file in definitions
definitionsNode.set(schemaPart.getKey(), schemaPart.getValue().without("$schema"));
}
return consolidatedSchema.toPrettyString();
}
private ObjectNode getSchemaWithResolvedParts(String schemaPath) throws IOException {
ObjectNode entrySchema = (ObjectNode) this.objectMapper.readTree(SchemaMerger.loadResource(schemaPath));
this.resolveExternalReferences(entrySchema);
JsonNode definitionsNode = entrySchema.get("definitions");
if (definitionsNode instanceof ObjectNode) {
this.definitions.add((ObjectNode) definitionsNode);
entrySchema.remove("definitions");
}
return entrySchema;
}
private void resolveExternalReferences(JsonNode schemaPart) throws IOException {
if (schemaPart instanceof ObjectNode || schemaPart instanceof ArrayNode) {
// recursively iterate over all nested nodes
for (JsonNode field : schemaPart) {
this.resolveExternalReferences(field);
}
}
if (!(schemaPart instanceof ObjectNode)) {
return;
}
JsonNode reference = schemaPart.get("$ref");
if (reference instanceof TextNode) {
String referenceValue = reference.textValue();
if (!referenceValue.startsWith("#")) {
// convert reference to separate file to entry in definitions
((ObjectNode) schemaPart).put("$ref", "#/definitions/" + referenceValue);
if (!this.schemas.containsKey(referenceValue)) {
this.schemas.put(referenceValue, this.getSchemaWithResolvedParts(referenceValue));
}
}
}
}
private static String loadResource(String resourcePath) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
try (InputStream inputStream = SchemaMerger.class.getResourceAsStream(resourcePath);
Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
while (scanner.hasNext()) {
stringBuilder.append(scanner.nextLine()).append('\n');
}
}
return stringBuilder.toString();
}
}
Calling new SchemaMerger().createConsolidatedSchema("customer.json") results in the following schema being generated:
{
"$schema" : "http://json-schema.org/draft-07/schema#",
"type" : "object",
"properties" : {
"billing_address" : {
"$ref" : "#/definitions/address.json"
}
},
"definitions" : {
"address.json" : {
"type" : "object",
"properties" : {
"street_address" : {
"type" : "string"
},
"city" : {
"type" : "string"
},
"state" : {
"type" : "string"
}
},
"required" : [ "street_address", "city", "state" ]
}
}
}
This should give you a starting point from which to build what you need.
Refer: this post. I have posted a possible solution.
Though, as mentioned, i have not yet tried it out myself.
I'm trying to deserialize a JSON object (from JIRA REST API createMeta) with unknown keys.
{
"expand": "projects",
"projects": [
{
"self": "http://www.example.com/jira/rest/api/2/project/EX",
"id": "10000",
"key": "EX",
"name": "Example Project",
"avatarUrls": {
"24x24": "http://www.example.com/jira/secure/projectavatar?size=small&pid=10000&avatarId=10011",
"16x16": "http://www.example.com/jira/secure/projectavatar?size=xsmall&pid=10000&avatarId=10011",
"32x32": "http://www.example.com/jira/secure/projectavatar?size=medium&pid=10000&avatarId=10011",
"48x48": "http://www.example.com/jira/secure/projectavatar?pid=10000&avatarId=10011"
},
"issuetypes": [
{
"self": "http://www.example.com/jira/rest/api/2/issueType/1",
"id": "1",
"description": "An error in the code",
"iconUrl": "http://www.example.com/jira/images/icons/issuetypes/bug.png",
"name": "Bug",
"subtask": false,
"fields": {
"issuetype": {
"required": true,
"name": "Issue Type",
"hasDefaultValue": false,
"operations": [
"set"
]
}
}
}
]
}
]
}
My problem is: I don't know the keys into "fields" (in the example below "issuetype", "summary", "description", "customfield_12345").
"fields": {
"issuetype": { ... },
"summary": { ... },
"description": { ... },
"customfield_12345": { ... }
}
It would be awesome if I could deserialize it as an array with the key as "id" in my POJO so the above example will looke like the following:
class IssueType {
...
public List<Field> fields;
...
}
class Field {
public String id; // the key from the JSON object e.g. "issuetype"
public boolean required;
public String name;
...
}
Is there a way I can achieve this and wrap in my model? I hope my problem is somehow understandable :)
If you don't know the keys beforehand, you can't define the appropriate fields. The best you can do is use a Map<String,Object>.
If there are in fact a handful of types, for which you can identify a collection of fields, you could write a custom deserializer to inspect the fields and return an object of the appropriate type.
I know it's old question but I also had problem with this and there are results..
Meybe will help someone in future : )
My Response with unknow keys:
in Model Class
private JsonElement attributes;
"attributes": {
"16": [],
"24": {
"165": "50000 H",
"166": "900 lm",
"167": "b.neutr.",
"168": "SMD 3528",
"169": "G 13",
"170": "10 W",
"171": "230V AC / 50Hz"
}
},
So I also checked if jsonElement is jsonArray its empty.
If is jsonObject we have data.
ProductModel productModel = productModels.get(position);
TreeMap<String, String> attrsHashMap = new TreeMap<>();
if (productModel.getAttributes().isJsonObject())
{
for (Map.Entry<String,JsonElement> entry : productModel.getAttributes().getAsJsonObject().entrySet())
{
Log.e("KEYS", "KEYS: " + entry.getKey() + " is empty: " + entry.getValue().isJsonArray());
if (entry.getValue() != null && entry.getValue().isJsonObject())
{
for (Map.Entry<String, JsonElement> entry1 : entry.getValue().getAsJsonObject().entrySet())
{
Log.e("KEYS", "KEYS INSIDE: " + entry1.getKey() + " VALUE: " + entry1.getValue().getAsString());
// and there is my keys and values.. in your case You can get it in upper for loop..
}
}
}
There is a perfectly adequate JSON library for Java that will convert any valid JSON into Java POJOs. http://www.json.org/java/
I need to parse the following JSON in Java using Gson Library. Can anyone help me as I am new to JSON?
alarmEvent = {
"version" : "1.0"
"type" : "ALARM",
"nodeId" : "",
"timeStamp" : "",
"params" : {
"paramId" : "",
"alarmType" : "",
"category" : "",
"source" : "",
"parameter": "",
"alarm" : "",
"alias" : "",
"duration" : ""
}
}
You can create an AlarmEvent class, containing a member for each field you expect to see in the JSON object. For example:
class AlarmEvent {
private String version;
private String type;
....
}
Then, you can instantiate an object of this type as follows:
AlarmEvent a = new Gson().fromJson(json, AlarmEvent.class);
You can now access the fields directly as a.version, a.type, etc.
JsonObject jobj = new Gson().fromJson(json, JsonObject.class);