Kapsh
Kapsh

Reputation: 22071

json client in java for Restful service

Typically I have been using xml web services and have used JAXB for marshalling/unmarshalling the xml. In this case, I have an xml schema for generating the classes and then at runtime I simply deal with java objects and not with xml since that unmarshalling is done under the covers for me.

What sort of libraries exist for doing something similar in json? I have to make an http Get call that returns a list of json objects and I am not sure what my java client should look like. What are the best practices here?

Thanks.

Upvotes: 0

Views: 2824

Answers (3)

Java Man
Java Man

Reputation: 1860

String url = "www.abc.com/products/1"; // 1 = product number
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.addHeader("User-Agent", USER_AGENT);
request.addHeader(BasicScheme.authenticate(
new UsernamePasswordCredentials("username", "password"), "UTF-8", false));
HttpResponse response = client.execute(request);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
data = new String(rd.readLine());

Now you have to create an object of the JSON library to parse the data or fetch particular data.

try {
        obj = new JSONObject(data);
        System.out.println("Final Data" + data);
        String category = obj.getString("product");
        System.out.println("category " + category);
}
} catch (JSONException ex) {
        System.out.println(ex);
    }

Use the org.codehaus.jettison.json library to deal with JSON data.

Upvotes: 0

Dmitry Negoda
Dmitry Negoda

Reputation: 3189

If you need to create both RESTful service and its client, then I would prefer rest4j. You can describe your RESTful service using XML and implement your service as it was a plain Spring bean. You can then also generate documentation and java/python/php/c# client libraries. Marshaling and unmarshalling is done under the hood.

And there is a way to flexibly map your internal Java objects into external JSON representation, like renaming a property, exporting only a subset of properties etc.

Upvotes: 0

Rahul
Rahul

Reputation: 21104

There are a lot of Java libraries out there that parse JSON. The simplest one to use is the one by org.json. For a list of various JSON parsing libraries take a look at (http://json.org)

If you have used JAXB to marshall / unmarshall value objects (POJO's) then you can also take a look at Jackson which uses JAXB annotations to determine what your POJO's representation in JSON should look like. (http://jackson.codehaus.org/)

Essentially you would need to make a HTTP GET request for your JSON, parse the request using a JSON parser and convert them into a convenient representation in Java. You can use the Apache Commons HttpClient libraries and JSON parsers in conjunction.

Upvotes: 1

Related Questions