MOXy support for JSON Pointer (RFC6901) in Jersey - java

I'm trying to marshal a recursive bean to JSON with MOXy in Jersey, following the specification of RFC6901 aka JSON Pointer.
E.g., I'd like to marshal this:
public class Bean {
public Integer id;
public String name;
public Bean other;
public List<Bean> next;
}
x = new Bean(123, "X");
a = new Bean(456, "A");
x.other = a;
x.next.add(x);
x.next.add(a);
into this:
{
"id": 123,
"name": "X",
"a": { "id": 456, "name": "A", "next": [ ] },
"next": [
{ "$ref": "#" },
{ "$ref": "#/a" }
]
}
and then unmarshal this JSON to the original bean. Does someone have any suggestion/solution to this problem?

Related

How to generate JsonSchema As Array from Java Class

I'm generating JsonSchema from Java class using fasterxml.jackson.
The generated Jsonschema will be as below
{
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
}
}
}
My code to generate JsonSchema
public static String getJsonSchema(Class definitionClass) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper().disable(
MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS);
JavaType javaType = mapper.getTypeFactory().constructType(definitionClass);
JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(mapper);
JsonSchema schema = schemaGen.generateSchema(javaType);
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
}
I tried to use ArraySchema arraySchema = schema.asArraySchema(); but it generates invalid schema.
My expected JsonSchema should be like below
{
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
}
}
}
}
TL;DR: Call getJsonSchema(MyClass[].class)
Works fine if we simply tell it to generate the schema of a Java array.
To demo, I created a MyClass class fitting the shown schema. I used public fields for simplicity of the demo, but we'd use private fields and public getter/setter methods in real life.
class MyClass {
public String id;
public String name;
}
Now, to show that we get the same result as in the question, we call it with MyClass.class:
System.out.println(getJsonSchema(MyClass.class));
Output
{
"type" : "object",
"id" : "urn:jsonschema:MyClass",
"properties" : {
"id" : {
"type" : "string"
},
"name" : {
"type" : "string"
}
}
}
Now, we want the schema to be an array of those, so we will instead call it using MyClass[].class.
System.out.println(getJsonSchema(MyClass[].class));
Output
{
"type" : "array",
"items" : {
"type" : "object",
"id" : "urn:jsonschema:MyClass",
"properties" : {
"id" : {
"type" : "string"
},
"name" : {
"type" : "string"
}
}
}
}
The above was tested using jackson-module-jsonSchema-2.10.3.jar.

Java - Spring return JSON object / array

I have a basic Rest Controller which returns a list of models in json to the client:
#RestController
public class DataControllerREST {
#Autowired
private DataService dataService;
#GetMapping("/data")
public List<Data> getData() {
return dataService.list();
}
}
Which returns data in this format:
[
{
"id": 1,
"name": "data 1",
"description": "description 1",
"active": true,
"img": "path/to/img"
},
// etc ...
]
Thats great for starting, but i thought about returning data of this format:
[
"success": true,
"count": 12,
"data": [
{
"id": 1,
"name": "data 1",
"description": "description 1",
"active": true,
"img": "path/to/img"
},
{
"id": 2,
"name": "data 2",
"description": "description 2",
"active": true,
"img": "path/to/img"
},
]
// etc ...
]
But i am not sure about this issue as i can not return any class as JSON... anybody has suggestions or advices?
Greetings and thanks!
"as i can not return any class as JSON" - says who?
In fact, that's exactly what you should do. In this case, you will want to create an outer class that contains all of the fields that you want. It would look something like this:
public class DataResponse {
private Boolean success;
private Integer count;
private List<Data> data;
<relevant getters and setters>
}
And your service code would change to something like this:
#GetMapping("/data")
public DataResponse getData() {
List<Data> results = dataService.list();
DataResponse response = new DataResponse ();
response.setSuccess(true);
response.setCount(results.size());
response.setData(results);
return response;
}

Nested json serialization in java

I have a Class like so:
public class Wrapper<T>{
#JsonProperty
public Creds credentials;
public T data;
}
which, when serialized returns JSON like so:
{
"credentials" : {
"token": "xxxxx"
},
"data": {
"A": "3",
"Sub": {
"X": "something",
"Y": "something else"
}
}
}
I would like to move the contents of "data" up and return the JSON like so:
{
"credentials" : {
"token": "xxxxx"
},
"A": "3",
"Sub": {
"X": "something",
"Y": "something else"
}
}
Any pointers on how to achieve that? I've tried using the attribute below and overriding the toString on each Type of 'T', but that did not work.
#JsonSerialize(using = ToStringSerializer.class)
The solution was to add the following attribute to the "data" property.
#JsonUnwrapped

How To Use Jackson's #JsonIdentityInfo for Deserialization of directed Graphs?

I want to use Jackson 2.3.3 for Deserialization/Serialization of directed graphs. The structure I came up with is roughly the following:
public Class Graph {
private final Set<Node> nodes;
public Graph(Set<Node> nodes) { ... }
public Set<Node> getNodes() { ... }
}
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "name")
public Class Node {
private final String name;
private final Set<Edge> edges;
public Node(String name, Set<Edge> edges) { ... }
public String getName() { ... }
public Set<Edge> getEdges() { ... }
}
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "name")
public Class Edge {
private final String name;
private final Node successor;
public Edge(String name, Node successor) { ... }
public String getName() { ... }
public Node getSuccessor() { ... }
}
And I expect to have this JSON-Structure:
{
"graph": [{
"name": "A",
"edges": [{
"name": "0",
"successor": "B"
}, {
"name": "1",
"successor": "A"
}]
}, {
"name": "B",
"edges": [{
"name": "0",
"successor": "A"
}, {
"name": "1",
"successor": "B"
}]
}]
}
But I get the following error while deserialization (even with annotation #JsonProperty("name") at the Getters):
com.fasterxml.jackson.databind.JsonMappingException: Invalid Object Id definition for some.package.graph.Node: can not find property with name 'name'
I have found some solutions for Jackson 1.6 with Back-Reference Annotations, but I'd like to use the new Jackson 2.x Annotation, as it was advertised so much in the API Update from 1.9 to 2.0 of Jackson.
What point am I missing here? Thanks for constructive answers in advance.
EDIT
(Removed my answer from here to the Answer section)
I got kind of blind of staring too long at it. Here's what's gone wrong:
The Serialization actually worked as intended. What didn't work was the Deserialization, because Jackson wasn't able to instantiate my Node-Object. I simply forgot to annotate the parameters of the constructor methods correctly.
I was now facing another problem. The generated JSON now looked like this:
"graph": {
"nodes": [{
"name": "B",
"edges": [{
"label": "1",
"successor": "B"
}, {
"label": "0",
"successor": {
"name": "A",
"edges": [{
"label": "1",
"successor": "A"
}, {
"label": "0",
"successor": "B"
}]
}
}]
}, "A"]
}
So far so good. But during mapping, Jackson confronts me with this Error:
java.lang.IllegalStateException: Could not resolve Object Id [B] (for [simple
type, class some.package.graph.Node]) -- unresolved forward-reference?
I even changed the Label of the edges because I thought the same property name might confuse Jackson here, but that didn't help either...
My guess here is that Jackson can't reference the Node B, because it is still being constructed (you could say it is actually some kind of root in this example). The only way to fix this seems to construct all the Nodes without the edges and inject them in a second step.

deserialize Json tree to objects in Java for structure of android app

I'm programming one android list-detail application and I have to load app structure from json. I'm trying to deserialize non-optimal json with Gson (Java) to objects, from that I'm going to dynamically generate fragments (I hope it can be done :-) ).
I have tabs within main FragmentActivity and one tab has own fragment and own json. Every tabs has own fragmentstack for controlling with back and up button.
I have this json:
{
"data": [],
"children": [
{
"data": {
"id": "5",
"deep": "0",
"url": "compare",
"type": "navigation",
"name": "Vergleich",
"text": null,
"number": null
},
"children": [
{
"data": {
"id": "12",
"deep": "1",
"url": "information",
"type": "navigation",
"name": "information",
"text": null,
"number": null
},
"children": []
},
{
"data": {
"id": "13",
"deep": "1",
"url": "application",
"type": "navigation",
"name": "application",
"text": null,
"number": null
},
"children": []
}
]
}
]
}
and I created this classes for gson:
public class StructureItem {
StructureData data;
ArrayList<StructureItem> children;
}
public class StructureData {
public int id;
public int deep;
public String url;
public String type;
public String name;
public String text;
public String number;
}
I tried to create Object with:
String s = LoadJson();
Gson gson = gsonBuilder.create();
StructureItem root = gson.fromJson(s, StructureItem.class);
But cannot succeed.
How would you solve my problem? Any easy solution?
It would be awesome has some notes for this.
I'm programming for couple years, but this is my first android project. Quite monstrous framework!
Try to replace ArrayList<StructureItem> to StructureItem[] in class StructureItem.

Categories

Resources