Converting JSON to Java Object in RESTful app [duplicate] - java

I have to integrate our j2ee application with a REST webservice. And I wanted to use the RestEasy JAX-RS implementation from JBoss. The webservice returns an array in JSON format. I've this piece of code:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://myservices.com/schemes/all");
Response response = target.request().get();
Can I map this "response" object to List<Scheme> using RestEasy? Thanks

Provided that your JSON provider is capable of converting JSON to appropriate entities, then yes. The get method you call in the code has an overloaded version which accepts the class of entity to which the result is to be converted. Since there are problems with serializing certain collections' implementations, your type has to be wrapped in GenericType class, like that:
List<Scheme> schema = [...].get(new GenericType<List<Scheme>>(){});
The above method should work with just about every JAX-RS-compliant implementation.
You can also use Jackson library, which allows you (amongst other things) to pass collections without need of wrapping them.

Related

Preserve Generics when generating JSON schema

I'm using jackson-module-jsonSchema and jsonschema2pojo API.
Brief explanation: I'm trying to json-schemify my server's Spring controller contract objects (objects that the controllers return and objects that they accept as parameters) and package them up to use with a packaged retrofit client in order to break the binary dependency between the client and server. The overall solution uses an annotation processor to read the Spring annotations on the controller and generate a retrofit client.
I've got it mostly working, but realized today I've got a problem where generic objects are part of the contract, e.g.
public class SomeContractObject<T> {
...
}
Of course, when I generate the schema for said object, the generic types aren't directly supported. So when I send it through the jsonschema2pojo api I end up with a class like so:
public class SomeContractObject {
}
So my question is simple but may have a non-trivial answer: Is there any way to pass that information through via the json schema to jsonschema2pojo?

How to use Couchbase Java Client in a Dropwizard Project?

I've been looking at the couchbase-java-client project and wondering whether it's possible to use it inside of a dropwizard project.
It seems like it'd be a natural fit, because couchbase is basically a JSON database, but the java client doesn't seem to be compatible with Jackson. As far as I can tell, the couchbase client library includes its own internal implementation of a JSON library that's incompatible with all the other java JSON libs out there, which is really weird.
I found a JacksonTransformers class that looked promising at first. But upon closer inspection, the library is using a shaded version of Jackson (with a rewritten package of com.couchbase.client.deps.com.fasterxml.jackson.core).
Anyhow, since dropwizard uses Jackson and Jersey for marshalling JSON documents through the REST API, what's the least-friction way of using the couchbase-java-client library? Is it even possible in this case?
It is definitely possible to use Couchbase with Dropwizard. The client SDK provides JSON manipulation objects for the developer's convenience but it also allows for delegating JSON processing to a library like Jackson or GSON.
Take a look at the RawJsonDocument class here.
Basically, you can use a Stringified JSON (coming out of any framework) to create one of those objects and the client SDK will understand it as a JSON document for any operation i.e.:
String content = "{\"hello\": \"couchbase\", \"active\": true}";
bucket.upsert(RawJsonDocument.create("rawJsonDoc", content));
It should be possible to make this work.
Client requests to dw server for Resource Person.
DW server requests to couchebase, gets a Pojo back representing Person or JSON representing person.
If it's JSON, create a POJO with Jackson annotations in DW and return that to client
If it's a special couchebase pojo, map that to a Jackson pojo and return to to client
A solution based on #CamiloCrespo answer:
public static Document<String> toDocument(String id, Object value,
ObjectMapper mapper) throws JsonProcessingException {
return RawJsonDocument.create(id, mapper.writeValueAsString(value));
}
Keep in mind, that you can't use a simply maper, like ObjectMapper mapper = new ObjectMapper(), with Dropwizard.
You can get it from Environment#getObjectMapper() in the Application#run() method, or use Jackson.newObjectMapper() for tests.
An example of using:
ObjectMapper mapper = Jackson.newObjectMapper();
User user = User.createByLoginAndName("login", "name");
bucket.insert(toDocument("123", user, mapper));

Java REST WebService

I'm trying to build a Java REST web service that will do some processing on a get request (eg. send get request with info, do some calculations, then send back an object with the results). Any ideas how I can set this up easily in Netbeans? I've been playing with the New->RESTful web service... feature, but can't seem to get it to return an object.
AFAIK you're supposed to return a string representation of the result. For example implementing the getXml() method:
/**
* Retrieves representation of an instance of services.GenericResource
* #return an instance of java.lang.String
*/
#GET
#Produces("application/xml")
public String getXml() {
return "<entry></entry>";
}
You could use an XML API to turn your objects into XML strings and return them.
What kind of object do you want to return...?
In java rest webservice you can return many kinds of objects like json,xml.
You can follow these tutorials for creating any kind of java rest webservice -
http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/
This link shows example of get request which returns a json object. You can browse there tutorials for any other requirements.
I haven't tried it in Netbeans, but I have done it using Intellij tho, using maven. Just used servlets to get the requests and used GSON to convert the outgoing java object to JSON and send it out.
This is the project I did with some of my colleges.

Restlet response type

How can I return Restlet response in desired format?
I am using the method:
#Get ("json")
public Address sendResponse(){
Address add = getAddress();
return add;
}
Right now I have to explicitly convert java object to a json string as a response to browser. Can't it be taken care by Restlet framework itself?
Spring MVC's Restful implementation can do it. I am looking similar implementation in Restlet too.
In fact, there are two ways to do that with Restlet:
the explicit one using JSON representations. The JSONRepresentation if you use objects from org.json or the JacksonRepresentation if you want JSON / Object mapping. You can find below an example:
#Get ("json")
public Representation sendResponse(){
Address add = getAddress();
return new JacksonRepresentation<Address>(address);
}
the implicit one using converter. In this case, it's the code you gave. You must have in your classpath an appropriate converter such as the one provided by the org.restlet.ext.jackson extension. It will detect that a JSON content needs to be returned and implicitly convert your Address object to a JSON content.
Just for hint, the json media specified in the GET annotation tells Restlet to use the associated method to handle the request when application/json is defined for conneg (content negociation) with the accept header.
Hope it helps you.
Thierry
Try setting the response type to application/json instead of just json. Normally, you need to specify the correct MIME type. As you say, if you set the MIME type correctly, other frameworks will do the conversion automatically.

Can the XPage JSON library automatically convert a Java Bean to a JSON representation?

I want to use the com.ibm.commons.util.io.json.* library which comes with the XPages runtime to serialise a Java Bean into JSON.
The question is can it do it automatically by just passing it the object - like you can with the Google library - http://code.google.com/p/google-gson/ or do you need to construct the JSON manually by which I mean passing the individual properties to construct the JSON.
Having trouble locating the documentation for this library, though I have seen some examples:
http://www.openntf.org/internal/home.nsf/project.xsp?action=openDocument&name=JSON%20and%20REST%20Samples
http://www-10.lotus.com/ldd/ddwiki.nsf/dx/Sending_requests_in_Java_dds10
Ideally we dont want to use a 3rd party library, even though it works great, because we need to modify the java security properties file which in turn gets wiped if the server gets upgraded.
The com.ibm.commons.util.io.json library is a genric library for converting JSON representations to Java objects, back and forth. By generic, I mean that it uses a factory to both browse and update the Java objects (see: JsonFactory). By implementing such a factory, and implementing the getter/setters for all the properties, one can serialize/deserialize any kind of objects.
The JSON library is equiped with a set of predefined factories:
JsonJavaFactory, that maps JSON Objects to Java Maps (with a extended version that uses a JsonJavaObject wrapper which is more convenient)
JsonJavaScriptFactory, that maps JSON objects to actual JavaScript objects (see: ObjectObject) and Java values (String, Integer...) to JavaScript values (FBSString, FBSNumber...). These objects can be directly used by the server side JS engine.
We don't have a factory for JavaBeans per say, but implementing such a factory should not be a big deal.
The ibm commons library for json works by constructing an object, then adding json properties to the object. It can not auto-serialize an object, and works really only with primitive data types.
I've attached some SSJS code to illustrate how to work with the class. It assumes recordMap is a java map instance with some beans in it, and each bean has 5 fields named fieldName1 through fieldName5. The code iterates through each bean in the map, retrieves the 5 fields, convert the values to JSON, then pushes them into array. Finally the array is put inside another json object that includes the count, and the array itself.
var jsonObjArr = [];
var itr:java.util.Iterator = recordMap.keySet().iterator();
while (itr.hasNext()) {
var record = recordMap.get(itr.next());
var jsonObj:com.ibm.commons.util.io.json.JsonJavaObject =
new com.ibm.commons.util.io.json.JsonJavaObject();
jsonObj.putJsonProperty("fieldName1", record.getFieldName1());
jsonObj.putJsonProperty("fieldName2", record.getFieldName2());
jsonObj.putJsonProperty("fieldName3", record.getFieldName3());
jsonObj.putJsonProperty("fieldName4", record.getFieldName4());
jsonObj.putJsonProperty("fieldName5", record.getFieldName5());
jsonObj.putJsonProperty("fieldName6", record.getFieldName6());
jsonObjArr.push(com.ibm.commons.util.io.json.JsonGenerator
.toJson(com.ibm.commons.util.io.json.JsonJavaFactory.instanceEx, empr));
};
var jsonString = "{" +
"count:" + #Text(jsonObjArr.length) + "," +
"employees:" + "[" + jsonObjArr.join(",") + "]" +
"}";
return jsonString;
Hope this helps..

Categories