Jackson annotations tutorials? - android

Does somebody aware of some good jackson annotations tutorials? Especially, how do you parse json array using jackson annotations?
Suppose I have json like this:
{
...
"item1": "aaa",
"item2": "bbb",
"fl": [
{
"item3": "ccc",
"item4": "ddd"
}
]
}
How does one parse json including array using jackson annotations?

I assume you are asking about how to map JSON into Java objects (parsing typically refers to lower level activity of decoding JSON content stream into another representation, which may or may not be set of objects).
With Jackson (as well as many other libs, Genson, GSON etc), you have choice of either binding it into a POJO with matching structure, say:
public class Value {
public String item1; // or some other type one can bind from JSON String
public String item2; // can alternatively use getters/setters instead of public fields
public List<EntryType> f1;
}
public class EntryType {
public String item3;
public String item4;
}
or reading it as a Tree representation like so:
JsonNode rootNode = mapper.readTree(inputSource);
In latter case, you need to traverse the tree nodes to find your data.
As to annotations: you only need to use annotations if you need to change default properties of binding; like mapping between JSON Object fields and POJO property names.
For Jackson-specific configuration including some of annotations, see Jackson-databind github project: https://github.com/FasterXML/jackson-databind/

There are three ways to parse json using Jackson -
Using a streaming Parser. (http://www.studytrails.com/java/json/java-jackson-json-streaming.jsp)
Parsing Json to a tree model - http://www.studytrails.com/java/json/java-jackson-json-tree-parsing.jsp
Data binding with our without annotations - data binding, data binding with filters, Polymorphic data binding

Related

Is it possible to use other variable names in Realm?

I would like to parse a JSON object and map it to a RealmObject directly using the method createObjectFromJson.
My JSON is looking like that:
"data": {
"default": "a string"
}
So I make a RealmObject class like this
public class Data extends RealmObject{
private String default;
// GETTERS AND SETTERS
}
So I can call the method
realm.createObjectFromJson(Data.class, json);
Obviously the problem here is that I cannot use the keyword default to name my variable.
Is there any way to annotate my variable in Realm to use an alias ?
I'm aware that I can modify my input JSON but the aim is not to do it so I can have a generic method to map my JSON to a RealmObject.
Realm does not support renaming variables, but JSON libraries like GSON and Jackson do. You should look into those instead and then use copyToRealm or copyToRealmOrUpdate instead of createObjectFromJson

Is there any way to directly handle json in android/java without convert [duplicate]

I was wondering if somewhere out there exists a java library able to query a JSONObject. In more depth I'm looking for something like:
String json = "{ data: { data2 : { value : 'hello'}}}";
...
// Somehow we managed to convert json to jsonObject
...
String result = jsonObject.getAsString("data.data2.value");
System.out.println(result);
I expect to get "hello" as output.
So far, the fastest way I have found is using Gson:
jsonObject.getAsJsonObject("data").getAsJsonObject().get("data2").getAsJsonObject("value").getAsString();
It's not actually easy to write and read. Is there something faster?
I've just unexpectedly found very interesting project: JSON Path
JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document.
With this library you can do what you are requesting even easier, then my previous suggestion:
String hello = JsonPath.read(json, "$.data.data2.value");
System.out.println(hello); //prints hello
Hope this might be helpful either.
While not exactly the same, Jackson has Tree Model representation similar to Gson:
JsonNode root = objectMapper.readTree(jsonInput);
return root.get("data").get("data2").get("value").asText();
so you need to traverse it step by step.
EDIT (August 2015)
There actually is now (since Jackson 2.3) support for JSON Pointer expressions with Jackson. So you could alternatively use:
return root.at("/data/data2/value").asText();
First of all, I would recommend consider JSON object binding.
But in case if you get arbitrary JSON objects and you would like process them in the way you described, I would suggest combine Jackson JSON processor along with Apache's Commons Beanutils.
The idea is the following: Jackson by default process all JSON's as java.util.Map instances, meanwhile Commons Beanutils simplifies property access for objects, including arrays and Map supports.
So you may use it something like this:
//actually it is a Map instance with maps-fields within
Object jsonObj = objectMapper.readValue(json, Object.class);
Object hello = PropertyUtils.getProperty(jsonObj, "data.data2.value")
System.out.println(hello); //prints hello
You can use org.json
String json = "{ data: { data2 : { value : 'hello'}}}";
org.json.JSONObject obj = new org.json.JSONObject(json);
System.out.println(obj.query("/data/data2/value"));
I think no way.
Consider a java class
class Student {
Subject subject = new Subject();
}
class Subject {
String name;
}
Here if we want to access subject name then
Student stud = new Student();
stud.subject.name;
We cant access name directly, if so then we will not get correct subject name. Like here:
jsonObject.getAsJsonObject("data")
.getAsJsonObject()
.get("data2")
.getAsJsonObject("value")
.getAsString();
If you want to use same like java object then use
ClassName classObject = new Gson().fromJson(JsonString, ClassName.class);
ClassName must have all fields to match jsonstring. If you have a jsonobject inside a jsonobject then you have to create separate class like I'm doing in Student and Subject class.
Using Java JSON API 1.1.x (javax.json) one can make use of new JavaPointer interface. Instance implementing this interface can be considered to some extend as kind of XPath expression analog (see RFC-6901 for details). So in your case you could write this:
import javax.json.*;
//...
var jp = Json.createPointer("/data/data2/value");
System.out.println(jp.getValue(jsonObject));
In 1.1.4 version of JSON there's also nice addition to JsonStructure interface (which is implemented by JsonObject and JsonArray), namely getValue(String jsonPointer). So it all comes down to this simple one-liner:
System.out.println(jsonObject.getValue("/data/data2/value"));

Android: convert Parcelable to JSON

I am working with socket.io library which emits messages to the socket.io server. The server expects JSON objects, arrays, etc. My original implementation used JSONOject and JSONArray datatypes. However, I would like to switch to using classes generated via Parceler library. The classes generated with library's annotations can be wrapped into Parcels. It seems like a very convenient way of managing such communication. However, is there a way to convert Parceler's class or a Parcel class into a JSON string or JSONObject/Array?
GSON library supports toJson method and I know that Retrofit does some magic with Parcels, JSON, and GSON.
i guess this will help you,
Create a class with getters and setters method for example
class A
{
int b;
void setb(int x){this.b = x;}
int getb(){return this.b}
}
than you can create json from the object of this class:
new Gson().toJson(a)
Or object from json:
a = new Gson().fromJson(data, A.class);

FasterXML Jackson ObjectMapper for .Net MVC4 JSON POST Result Type Objects

I am sharing this for others working between Java clients and Web Services from .Net MVC4 and using RoboSpice and FasterXML Jackson frameworks. I could not find good information on stackoverflow on how to set up the JSON POJO class for proper object mapping for the POST result object. For POST operations the RESULT JSON comes back with the structure from the .Net web services:
{"ClassName":{"attribute_one":1,""attribute_two":1,"....}}
I could not figure out how to get the FastXml Jackson ObjectMapper readValue parsing to work. I got an empty result object after parsing with all the properties set to null or default values..., or invalid property name for the class name if I turned off the JsonIgnoreProperties.
The following POJO object definition finally worked for me. It has an outer class that matches the ClassName in the Result and then an inner static class for mapping the Single Result Object into a Java Class Object:
public class ClassNameOuter {
#JsonProperty("ClassName")
public ClassName _ClassName;
public ClassName get_ClassName() {
return _ClassName;
}
public void set_ClassName(ClassName _ClassName) {
this._ClassName = _ClassName;
}
#JsonIgnoreProperties(ignoreUnknown=true)
public static class ClassName {
#JsonProperty("attribute_one")
public long attribute_one;
#JsonProperty("attribute_two")
public long attribute_two;
For the experts out there on Jackson and Robospice....please share if there is a better way.
RoboSpice doesn't support yet parsing of XML using Jackson. It provides a module to parse XML using SimpleXMLSerializer but not jackson.
Can you indicate which classes of Jackson you used, I would add a module soon to RS.

GSON Dynamic Class Binding

I'm currently using GSON to parse my JSON to Objects. I was using the standard way like :
Result response= gson.fromJson(reader, Result.class);
Result can be a very complex object with other Complex objects, with up to 5 levels of complex objects. But I have no issues with that.
My Question is : I would like to be able to have in some objects an attribute with a flexible type.
For example :
class Class1 {
String hello;
}
class Class2 {
String world;
}
class Class3 {
Class<?> (= class1 or class2) hello;
}
// Parsing time
Class<?> response= gson.fromJson(reader, Class3.class);
try {
Class1 ret = (Class1)response;
} catch ... {
Class2 ret = (Class2)response;
}
Hope it's clear enough.
Unfortunately, the latest release of Gson (2.0) still doesn't have built-in support for an easy configuration to provide polymorphic deserialization. So, if Gson must be used (instead of an API that has such built-in support, like Jackson -- using which I've posted complete examples for polymorphic deserialization at http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html), then custom deserialization processing is necessary.
For deserialization to polymorphic types, something in the JSON must be present to identify which concrete type to deserialize to.
One approach would be to have an element in the JSON dedicated to just this purpose, where the deserialization code selects the correct type based on the value of the special-purpose element. For example:
{"type":"Class1","hello":"Hi!"} --> deserializes to Class1 instance
{"type":"Class2","world":"Earth"} --> deserializes to Class2 instance
Another approach would be to just switch on the presence of particular JSON element names, though instead of try-catch blocks as demonstrated in the original question, I'd just use if-statements.
See Gson issue 231 for more on this topic, as well as possible information on when a built-in polymorphic deserialization facility might be included in Gson.
Another StackOverflow.com post with an example of polymorphic deserialization with Gson is Polymorphism with gson

Categories

Resources