How To Serialize Complex Json Object To Querystring For Http Get Using Jackson?
Solution 1:
[Edit] NOTE: I misunderstood the question. My answer below answers how to parse the JSON and get a Java object. You wanted to get the Key value pairs where JSON is the value for the object. The below answer will not answer that question. Sorry for the confusion.
You can fix this issue by using Jackson annotations to the java model and adding a "type" to the JSON object. You might want to research it for your purposes but here is an example from some code I have done in the past.
public classRequirement {
private String title;
private String reqId;
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type") @JsonSubTypes({
@JsonSubTypes.Type(value=CountRequirementList.class, name="COUNT"),
@JsonSubTypes.Type(value=AndRequirementList.class, name="AND"),
@JsonSubTypes.Type(value=OrRequirementList.class, name="OR")
})
private List<RequirementList> fulfillments;
where the baseObject
is the RequirementList
and the class names are types of the requirements
list.
To make things easier going back and forth from JSON, it is sometimes convenient to just add a type to the object. I have included more code below in case it helps. (note: I did not include all the getters and setters that are needed for Jackson)
publicabstractclassRequirementList {
privateLogicTypetype;
privateString id;
privateString title;
privateString description;
protected float requiredCount; //For count type subclass. Designed to be count of creditsprivateList<Object> fulfillments;
}
publicclassOrRequirementListextendsRequirementList {
publicOrRequirementList() {
super();
super.setType(LogicType.OR);
}
}
Solution 2:
See my answer for this question How to serialize ANY Object into a URI?. You have to add only URL encoding to my solution. For example you can use UrlEncoder#encode(String s, String enc)
method.
Solution 3:
OK,
Here is the holder object:
publicclassComplexJacksonObjectextendsBaseJsonObject{
publicint Start;
publicint Count;
public Person MyPerson;
publicList<String> Strings;
publicclassPersonextendsBaseJsonObject{
publicString Firstname;
publicString Lastname;
public Address Where;
}
publicclassAddressextendsBaseJsonObject{
publicString Street;
publicint Number;
}
}
Here is how I initialize it:
ComplexJacksonObject cjo = new ComplexJacksonObject();
cjo.Count = 1;
cjo.Start = 2;
cjo.Strings = new ArrayList<String>();
cjo.Strings.add("One");
cjo.Strings.add("Two");
cjo.MyPerson = cjo.new Person();
cjo.MyPerson.Firstname = "Fi\",=[]{}rst";
cjo.MyPerson.Lastname = "Last";
cjo.MyPerson.Where = cjo.new Address();
cjo.MyPerson.Where.Street = "Street";
cjo.MyPerson.Where.Number = 15;
String result = cjo.toQueryString();
// Strings=%5B%22One%22%2C%22Two%22%5D&MyPerson=%7BFirstname%3A"Fi%5C%5C%22%2C%3D%5B%5D%7B%7Drst"%2CLastname%3A%22Last%22%2CWhere%3A%7BStreet%3A%22Street%22%2CNumber%3A15%7D%7D&Start=2&Count=1
And finally the method that makes this happen:
publicStringtoQueryString() {
StringBuilder sb = newStringBuilder();
for (Field field : this.getClass().getDeclaredFields()) {
if (sb.length() > 0) {
sb.append("&");
}
Class cls = field.getType().getSuperclass();
// serializing my complex objects - they all inherit from BaseJsonObject classif (cls != null && cls.equals(BaseJsonObject.class)) {
BaseJsonObject bjo = (BaseJsonObject) getFieldValue(field);
String str = toJson(bjo, true);
sb.append(field.getName()).append("=").append(Uri.encode(str));
}
// serializing lists, they are all List<T>elseif (field.getType().equals(List.class)) {
List bjo = (List) getFieldValue(field);
String val = toJson(bjo, false);
sb.append(field.getName()).append("=").append(Uri.encode(val));
}
// serializing simple fieldselse {
Object bjo = getFieldValue(field);
String val = toJson(bjo, false).replaceAll("^\"|\"$", "");
sb.append(field.getName()).append("=").append(Uri.encode(val));
}
}
return sb.toString();
}
privateObjectgetFieldValue(Field field) {
try {
return field.get(this);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
returnnull;
}
privatestaticObjectMappergenerateMapper() {
ObjectMapper om = newObjectMapper();
// om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
om.setDateFormat(newJacksonSimpleDateFormat());
return om;
}
publicStringtoJson() {
try {
returngenerateMapper().writeValueAsString(this);
} catch (JsonProcessingException e) {
e.printStackTrace();
returnnull;
}
}
publicStringtoJson(Object o, boolean noQuoteProperties) {
try {
ObjectMapper om = generateMapper();
if (noQuoteProperties) {
om.configure(com.fasterxml.jackson.core.JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
om.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
}
return om.writeValueAsString(o);
} catch (JsonProcessingException e) {
e.printStackTrace();
returnnull;
}
}
Post a Comment for "How To Serialize Complex Json Object To Querystring For Http Get Using Jackson?"