Create JsonObject from #ResponseBody - json

#RequestMapping(value = "/dropDown", method = RequestMethod.GET)
public #ResponseBody
DropDown getList(Map<String, Object> map, HttpServletRequest request,
HttpServletResponse response) {
DropDown dropDown = new DropDown();
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
List<MapTable2> list = contactService.mapProcess();
for (MapTable2 table : list) {
Map<String, Object> dataRow = new HashMap<String, Object>(1);
dataRow.put("text", table.getProcess());
dataRow.put("value", table.getId());
dataRow.put("selected", false);
dataRow.put("description", table.getProcess());
dataRow.put("imageSrc", "image.jpg");
rows.add(dataRow);
}
dropDown.setRows(rows);
return dropDown;
}
I need to create following one
var ddData = [
{
text: "Facebook",
value: 1,
selected: false,
description: "Description with Facebook",
imageSrc: "http://dl.dropbox.com/u/40036711/Images/facebook-icon-32.png"
},
{
text: "Twitter",
value: 2,
selected: false,
description: "Description with Twitter",
imageSrc: "http://dl.dropbox.com/u/40036711/Images/twitter-icon-32.png"
}]
I know the issue with my above java coding , I'm not aware to create json array like above.
please check it and help me to correct it.
MapTable2 has ProcessId & ProcessName
public class MapTable2 {
private int id;
private String process;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProcess() {
return process;
}
public void setProcess(String process) {
this.process = process;
}
}

#theon is right.
Since you are using #Responsebody you can let Spring do the JSON conversion for you. Create a class that matches the objects in the JSON array:
public class SomeObject {
public String getText() { //... }
public int getValue() { //... }
public boolean getSelected { // ... }
public String getDescription { // ... }
public String getImageSrc { // ... }
}
Populate the objects and return it as a list from your controller:
#RequestMapping(value = "/dropDown", method = RequestMethod.GET)
#ResponseBody
public List<SomeObject> getList(Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
// Get the objects, return them in a list
}
Add the <mvc:annotation-driven /> or the #EnableWebMvc to your application config unless you have not already done so. Make sure that Jackson is available on your classpath and then Spring will automatically serialize your objects to JSON (if the request has Content-Type: application/json. Alternatively, the produces attribute can be added to the #RequestMapping annotation to always return JSON).

Well Use this library. It is very light weight (16KB) and does exactly what you need.
So in your case, you will be using JSONObject which internally extends HashMap
and do
JSONObject o = new JSONObject();
o.put("text","whatever text");
o.put("value",1);
o.put("selected",false);
//and so on
JSONArray arr = new JSONArray();
arr.add(o);
The above will give you this:
[
{
text: "Facebook",
value: 1,
selected: false,
description: "Description with Facebook",
imageSrc: "http://dl.dropbox.com/u/40036711/Images/facebook-icon-32.png"
}
]
To add more objects, add more JSONObjects in a loop to JSONArray
So as per your given code, just replace dataRow with 'JSONObject' and rows with JSONArray and thats it. In the end, to retrieve the string, do rows.toString().

Related

#RestController custom ResponseEntity - Jackson

What i'm trying to achieve here is to get a custom response from the RequestMapping, below is the structure of the json which I'm trying to get in case of an array of objects:
{
"error": false,
"message": "the message",
"data": [{},{},...]
}
and the below in case of object
{
"error": false,
"message": "the message",
"data": {}
}
The code is working fine but the problem is "data" will not always has an array, it may store an object, so what I tried is to create a custom POJO class which contains my custom response and when I want to annotate two attributes with same name i'm getting the below error
Could not find acceptable representation
And what if I create another class which will contain the same attributes but with an JsonObject not with array, is there any better way to achieve this ?
Below are my classes :
#JsonInclude(Include.NON_NULL)
public class JsonResponseObject<T> implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private boolean error;
private String message ;
#JsonProperty(value="data")
private ArrayList<T> array;
#JsonProperty(value="data")
private Object object ;
public JsonResponseObject() {
}
public boolean isError() {
return error;
}
public void setError(boolean error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public ArrayList<T> getArray() {
return array;
}
public void setArray(ArrayList<T> array) {
this.array = array;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
UserJsonController.java :
#RestController()
#RequestMapping(value = "/json")
public class UserJsonController {
#Autowired
private UserRepository userDAO;
#RequestMapping(value = "/users", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getUsers() {
ArrayList<Users> entityList = (ArrayList<Users>) userDAO.findAll();
JsonResponseObject<Users> jsonResponse = new JsonResponseObject<Users>();
jsonResponse.setError(false);
jsonResponse.setMessage("test");
jsonResponse.setArray(entityList);
return new ResponseEntity<>(jsonResponse, HttpStatus.OK);
}
#RequestMapping(value = "/users/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getUserByID(#PathVariable int id) {
JsonResponseObject<Users> jsonResponse = new JsonResponseObject<Users>();
jsonResponse.setError(false);
jsonResponse.setMessage("test");
jsonResponse.setObject(userDAO.findById(id).get());
return new ResponseEntity<>(jsonResponse, HttpStatus.OK);
}}

How to use specific custom objectMapper/JsonSerializer for specific requestMapping

I know thar Jackson allow us to use custom serializer for specific domain/entity/modle, like this:
#JsonSerialize(using = CustomSerializer.class)
public class SimpleDomain {
}
And, is there any idea to specify custom serializer for some requestMapping,
(only for the specific requestMapping(that method), not to set global objectMapper.) like this:
#RequestMapping(method = RequestMethod.GET, value = "hello")
#JsonSerialize(nullsUsing = NullToEmptyStrSerializer.class)
public #ResponseBody
Object get() {
return new HashMap<String, Object>() {{
put("aa", null);
put("bb", "");
}};
}
I execute the code above, it returns:
{
"aa": null,
"bb": ""
}
instead of:
{
"aa": "",
"bb": ""
}
which exactly i wanted.
NullToEmptyStrSerializer :
public class NullToEmptyStrSerializer extends JsonSerializer {
#Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
gen.writeString("");
}
}
Or, can i get HttpServletRequest in NullToEmptyStrSerializer, if yes, i can filter in NullToEmptyStrSerializer.
It may be a known limitation (#JsonSerialize with nullUsing option not working for String properties) and reported in this github issue.
It is scheduled to be released in jackson 2.9.3 and 2.8.11.
Fix will be in 2.9.3 but I also back-ported it in 2.8 branch in case
2.8.11 might be released at some point.
Finally, I found it out by myself.
I realized this point:
Or, can i get HttpServletRequest in NullToEmptyStrSerializer, if yes, i can filter in NullToEmptyStrSerializer.
My purpose :
Custom convert null to "" for specific Url(RequestMapping)
My solution :
Define a bean to keep ApplicationContext storing in a static field, also, a static getter:
#Component
public class ContextHolder {
private static ApplicationContext applicationContext;
#Resource
public void setApplicationContext(ApplicationContext applicationContext) {
ContextHolder.applicationContext = applicationContext;
}
public static ApplicationContext get(){
return applicationContext;
}
}
Define a bean below, this bean will create for every request, thus, i store ServletRequest in this bean.
#Component("servletRequestHolder")
#Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ServletRequestHolder {
#Resource
private HttpServletRequest request;
public HttpServletRequest getRequest(){
return request;
}
}
Then, a serializer is needed.
public class NullToEmptyStringSerializer extends JsonSerializer.None {
public static List<String> convertUrls = new ArrayList<String>(){{
add("/hello");
}};
#Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
HttpServletRequest request = ContextHolder.get().getBean(ServletRequestHolder.class).getRequest();
if (request != null) {
String currentUrl = request.getRequestURI();
boolean match = convertUrls.contains(currentUrl);
if (match) {
gen.writeString("");
} else {
gen.writeObject(null);
}
} else {
gen.writeObject(null);
}
}
}
Add the Serializer to objectMapper:
DefaultSerializerProvider.Impl sp = new DefaultSerializerProvider.Impl();
sp.setNullValueSerializer(new NullToEmptyStringSerializer());
objectMapper.setSerializerProvider(sp);
Finally, test it :
#GetMapping({"hello", "hello1"})
public Object get() {
return new HashMap<String, Object>() {{
put("a", null);
put("b", "");
}};
}
In case of requesting localhost:20000/hello, the client receive:
{
"aa": "",
"bb": ""
}
And for requesting localhost:20000/hello1, the client receive:
{
"aa": null,
"bb": ""
}

#JsonAnySetter, #JsonAnyGetter with DSL Json (De)/Serialization not taking values(always null)

Im using #JsonAnySetter and #JsonAnyGetter in my POJO class using my Custom serialization with DSL JSON class, the Map is initialized but the other properties are always null.
My POJO class:
#CompiledJson
public class Name {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Map<String,String> properties = new HashMap<String,String>();
public Name() {
// TODO Auto-generated constructor stub
}
#JsonAnyGetter
public Map<String, String> get() {
return this.properties;
}
#JsonAnySetter
public void set(String key, String value) {
this.properties.put(key, value);
}
De/Serializing using DSLJson serialize() and deserialize() methods. I do not see any error also, but properties remains null in JSON. I doubt if Jackson annotations are supported by DSL Json. :/
Spring Boot App with DSL Json and Jackson Annotations
UPDATE
I want to parse MyClass, which is a part of RootClass:
#Compiledjson
public class RootClass {
private String id;
private List<MyClass> myclass;
private AnotherCLass class2;
//getters and setter here
}
#CompiledJson
public class MyClass implements JsonObject {
private String name;
private Map<String, String> properties; //want this to behave like Jackson's #JsonAnySetter/Getter annotation.
//The implementation of MapConverter serializer you mentioned below.
}
The entire code parses through custom Message reader and writer.
While sending my JSON Body, It'll be like this :
{
"id" : "1234",
"myclass" :
[
{
"name" : "abcd",
//any dynamic properties I want to add will go here
"test" : "test1",
"anything" : "anything"
}
],
"class2" : "test5"
}
Thank you :)
DSL-JSON doesn't support such get()/set(string, string) method pairs.
It does understand Map<String, String> so if you expose properties it will work on that. But not in this kind of setup.
As of v1.1 you have two options for solving such problems, both of them are covered in example project
If you wish to reuse existing converters, your solution can look like this:
public static class MyClass {
private String name;
private Map<String, String> properties;
#JsonConverter(target = MyClass.class)
public static class MyClassConverter {
public static final JsonReader.ReadObject<MyClass> JSON_READER = new JsonReader.ReadObject<MyClass>() {
public MyClass read(JsonReader reader) throws IOException {
Map<String, String> properties = MapConverter.deserialize(reader);
MyClass result = new MyClass();
result.name = properties.get("name");
result.properties = properties;
return result;
}
};
public static final JsonWriter.WriteObject<MyClass> JSON_WRITER = new JsonWriter.WriteObject<MyClass>() {
public void write(JsonWriter writer, MyClass value) {
MapConverter.serialize(value.properties, writer);
}
};
}
}

Deserialise dynamic json types

I want to deserialize json which returns different data for different parameters.
Mostly I get:
{"posts": [{ "id" : 1, "name":"post1" },{ "id" : 1, "name":"post1" }]}
But sometimes the data returned is
{"posts": false}
I want to deserialize this as the following class
public class GetReaderResponse
{
public IEnumerable<ReaderPost> posts {get; set;}
}
public class ReaderPost
{
public int id {get; set;}
public string name{get; set;}
}
I am using C#,json.net but not able to do this correctly.
Newtonsoft.Json.JsonConvert.DeserializeObject<GetReaderResponse>(dataString);
You could build a custom converter, but an easy way to handle this would be to write an error handler that detects errors with the posts property:
var settings = new JsonSerializerSettings();
settings.Error += (sender, args) =>
{
if (string.Equals("posts", args.ErrorContext.Path, StringComparison.OrdinalIgnoreCase))
{
var currentObject = args.CurrentObject as GetReaderResponse;
currentObject.posts = Enumerable.Empty<ReaderPost>();
args.ErrorContext.Handled = true;
}
};
GetReaderResponse resp =
JsonConvert.DeserializeObject<GetReaderResponse>(json, settings);
This sets posts to Enumerable.Empty<ReaderPost>. This is still a little unsatisfying because if any error occurs, the property will be set. You could build a full custom converter to do this as a more complete solution.
Here's a converter that will take care of this:
public class PostsConverter : JsonConverter
{
public override object ReadJson(
JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
JToken val = JValue.ReadFrom(reader);
object result = null;
if (val.Type == JTokenType.Array)
{
result = val.ToObject<IEnumerable<ReaderPost>>();
}
else if (val.Type == JTokenType.Boolean)
{
result = Enumerable.Empty<ReaderPost>();
}
return result;
}
public override void WriteJson(
JsonWriter writer,
object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert (Type type)
{
return typeof(IEnumerable<ReaderPost>).IsAssignableFrom(type);
}
public override bool CanRead
{
get { return true; }
}
}
Usage:
var settings = new JsonSerializerSettings();
settings.Converters = new [] { new PostsConverter() };
GetReaderResponse resp =
JsonConvert.DeserializeObject<GetReaderResponse>(json, settings);
Example: https://dotnetfiddle.net/i9CXwp
By using JSON.NETs built in LINQ to JSON, you can try someting like this:
JObject jObject = JObject.Parse(json);
GetReaderResponse response = new GetReaderResponse();
if (jObject["posts"] is JArray)
response = jObject.ToObject<GetReaderResponse>();
// Do something with the response object.
where json variable is the json string you need to deserialize.
try this:
public class GetReaderResponse
{
public bool posts { get; set; }
public ReaderPost[] post { get; set; }
}
After reading #Ilija's comment I think I might have found a answer. I did not want not use string literals so I modified my class GetReaderResponse to look like below:
public class GetReaderResponse
{
public dynamic posts {get; set;}
public IEnumerable<ReaderPost> Posts
{
get
{
if (posts is bool )
return new ReaderPost[0];
return posts.ToObject<IEnumerable<ReaderPost>>();
}
}
}
Does this sound fine or does it look messy?

Jackson JSON Deserialization of MongoDB ObjectId

Ok, so first off here's the JSON that's returning from my web service. I'm trying to deserialize it into pojos after an asynchronous query in a ResponseHandler in my Android ContentProvider.
{"exampleList" : [{
"locationId" : "00001" ,
"owners" : [
{
"paidID" : { "$oid" : "50a9c951300493f64fbffdb6"} ,
"userID" : { "$oid" : "50a9c951300493f64fbffdb6"}
} ,
{
"paidID" : { "$oid" : "50a9c951300493f64fbffdb7"} ,
"userID" : { "$oid" : "50a9c951300493f64fbffdb7"}
}
]
}]}
At first, I was confused about the problem I was seeing, since I use the same Jackson-annotated beans for my web service as I do in my Android app--but then I realized that the owners object was never getting sent in the sample JSON to my web service (it skips the POJOs on my web service and gets added into the documents in mongoDB through atomic updates from the DAO).
So OK. Up to now, Jackson wasn't having to handle the owners object, and now that it is it is choking on it, namely:
JsonMappingException: Can not deserialize instance of java.lang.String out of
START_OBJECT token at [char position where you can find "userID" and "paidID"]
through reference chain [path to my Jackson bean which contains the owners class]
My Jackson bean has a wrapper, which is what that "exampleList" is all about:
public class Examples extends HashMap<String, ArrayList<Example>> {
}
And then the actual Example class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class Example implements Comparable<Example> {
#ObjectId #Id
private String id;
#JsonProperty(Constants.Example.location)
private String location;
#JsonProperty(Constants.Example.OWNERS)
private List<Owners> owners;
public int compareTo(Example _o) {
return getId().compareTo(_o.getId());
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public List<Example.Owners> getOwners() {
return owners;
}
public void setOwners(List<Example.Owners> owners) {
this.owners = owners;
}
public Example() {
}
#JsonCreator
public Example(#Id #ObjectId String id) {
this.id = id;
}
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Owners implements Comparable<Owners> {
#JsonProperty(Constants.Example.USERID)
private String userID;
#JsonProperty(Constants.Example.PAIDID)
private String paidID;
public Owners() {
}
public int compareTo(Owners _o) {
return getUserID().compareTo(_o.getUserID());
}
#ObjectId
public String getUserID() {
return userID;
}
#ObjectId
public void setUserID(String userID) {
this.userID = userID;
}
#ObjectId
public String getPaidID() {
return paidID;
}
#ObjectId
public void setPaidID(String paidID) {
this.paidID = paidID;
}
}
}
And finally, the code in the ResponseHandler where this is all failing (the 2nd line produces the JsonMappingException):
objectMapper = MongoJacksonMapperModule.configure(objectMapper);
mExamples = objectMapper.readValue(jsonParser, Examples.class);
I have a feeling the issue is that Jackson still doesn't know how to map those $oid, which are the mongoDB ObjectIds. The MongoJacksonMapper library is supposed to help that by providing the #ObjectId annotation and a way to configure the ObjectMapper to use that library, but it still isn't working. For some reason, it's still looking for the userID or paidID as a String, not an ObjectId. Any ideas?
Another alternative is
com.fasterxml.jackson.databind.ser.std.ToStringSerializer.
#Id
#JsonSerialize(using = ToStringSerializer.class)
private final ObjectId id;
This will result in:
{
"id": "5489f420c8306b6ac8d33897"
}
For future users: Use a custom jackson deserializer to convert $oid back to ObjectId.
public class ObjectIdDeserializer extends JsonDeserializer<ObjectId> {
#Override
public ObjectId deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode oid = ((JsonNode)p.readValueAsTree()).get("$oid");
return new ObjectId(oid.asText());
}
}
How to use:
ObjectMapper mapper = new ObjectMapper();
SimpleModule mod = new SimpleModule("ObjectId", new Version(1, 0, 0, null, null, null));
mod.addDeserializer(ObjectId.class, new ObjectIdDeserializer());
mapper.registerModule(mod);
YourClass obj = mapper.readValue("{your json with $oid}", YourClass.class);
My code had at least two problems that were pretty tough to track down answers to online, so I'll make sure to link here. Basically, child classes need a constructor in the parent class that calls Jackson's readValue() to map the child. As far as mongoDB $oid's go, you should create a separate MongoId class to represent these mongo objects, and follow a similar pattern as with the child class to map the data when it comes in for deserialization. Here's a blog post I found that describes this well and provides some examples.
Jackson does not know how to serialize an ObjectId. I tweaked Arny's code to serialize any ObjectId and provide this working example:
public class SerialiserTest {
private ObjectMapper mapper = new ObjectMapper();
public static class T {
private ObjectId objectId;
public ObjectId getObjectId() {
return objectId;
}
public void setObjectId(ObjectId objectId) {
this.objectId = objectId;
}
}
#Test
public final void serDeser() throws IOException {
T t = new T();
t.setObjectId(new ObjectId());
List<T> ls = Collections.singletonList(t);
String json = mapper.writeValueAsString(ls);
System.out.println(json);
SimpleModule mod = new SimpleModule("ObjectId", new Version(1, 0, 0, null, null, null));
mod.addDeserializer(ObjectId.class, new ObjectIdDeserializer());
mapper.registerModule(mod);
JavaType type = mapper.getTypeFactory().
constructCollectionType(List.class, T.class);
List<?> l = mapper.readValue(json, type);
System.out.println(l);
}
}
public class ObjectIdDeserializer extends JsonDeserializer<ObjectId> {
#Override
public ObjectId deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode n = (JsonNode)p.readValueAsTree();
return new ObjectId(n.get("timestamp").asInt(), n.get("machineIdentifier").asInt(), (short) n.get("processIdentifier").asInt(), n.get("counter").asInt());
}
}
There's an even easier way documented here which was a lifesaver for me. Now you can use the ObjectId in Java but when you go to/from JSON it'll be a String.
public class ObjectIdJsonSerializer extends JsonSerializer<ObjectId> {
#Override
public void serialize(ObjectId o, JsonGenerator j, SerializerProvider s) throws IOException, JsonProcessingException {
if(o == null) {
j.writeNull();
} else {
j.writeString(o.toString());
}
}
}
And then in your beans:
#JsonSerialize(using=ObjectIdJsonSerializer.class)
private ObjectId id;
I did it like this:
#Configuration
public class SpringWebFluxConfig {
#Bean
#Primary
ObjectMapper objectMapper() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializerByType(ObjectId.class, new ToStringSerializer());
builder.deserializerByType(ObjectId.class, new JsonDeserializer() {
#Override
public Object deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
Map oid = p.readValueAs(Map.class);
return new ObjectId(
(Integer) oid.get("timestamp"),
(Integer) oid.get("machineIdentifier"),
((Integer) oid.get("processIdentifier")).shortValue(),
(Integer) oid.get("counter"));
}
});
return builder.build();
}
}