Rest API consumption without using a response bean - java

I want to consume a rest service which returning bunch of values.
The bean look like follows.
Class Customer{
Name, Address, Age ---etc // Almost 200 fields are there. Including reference to many objects as well. So it is very hard to create a bean for accepting the response.
}
Is there any alternative way to consume the response.
Customer customer = restTemplate.getForObject(http://testurl);
This is not I need. I need any other way to consume the service without creating the bean.
Using Spring Boot,Java 8

You probably might want to try to get JSONObject on your client side if you don't want to create a heavyweight DTO. Something along the lines:
String str = restTemplate.getForObject("http://testurl", String.class);
JSONObject myCustomer = new JSONObject(str);
String name = myCustomer.getString("name");
JSONObject address = myCustomer.getJSONObject("address"); // if address is a composite object with city, street, etc...

You could get the response in a JSON format and use JSONObject class to extract the data.
Example:
String response = restTemplate.getJSONObject(http://testurl);
JSONObject params = new JSONObject(response);
if(params.has("Name"))
String customerName = params.getString("Name");

Related

Trouble with getting strings into JSON

My servlet recieves/loads multiple parameters from/for an article (price, id, count, name).
While they are saved in the session for other purposes I want to display them in a Shopping cart.
So my idea was to get all values into a json like this
{"id":1, "prductName":"article1"}
but my json always ends up empty.
I had two approaches:
String prname = request.getParameter("name");
String anz = String.valueOf(session.getAttribute("Anzahl"));
String prid = request.getParameter("id");
String price = request.getParameter("price");
These are my parameters:
First try:
class ToJson{
String prname1 = String.valueOf(session.getAttribute("prname"));
String anz1 = String.valueOf(session.getAttribute("Anzahl"));
String prid1 = String.valueOf(session.getAttribute("id"));
String price1 = String.valueOf(session.getAttribute("price"));
}
ToJson obj = new ToJson();
Jsonb jsonb = JsonbBuilder.create();
String jsn1 = jsonb.toJson(obj);
Ends up with: {}
Second try:
ArrayList<String> ar = new ArrayList<String>();
ar.add(prname);
ar.add(price);
ar.add(prid);
ar.add(anz);
ToJson obj = new ToJson();
Jsonb jsonb = JsonbBuilder.create();
String jsn = jsonb.toJson(ar);
Ends up with: ["P1neu","25","1","145"]
It isn't in a format I wanted and I also don't know how to access the seperate values here, I tried jsn[1] but it didnt work.
Could you help me, please?
To your first question, why JSON object is printing empty:
You are missing getters & setters in the ToJSON class for JSON Builder/Parser to access the properties/fields, and that's why its printing as empty object.
To your second question, how do I access JSON properties:
JSON representation is a natively a string representation, and you can't read part of string as jsn[1].
For reading JSON object properties, you convert it into POJO using available any of preferred open source parser libraries like Jacksons, Gson etc. And then access POJO properties using standard java getter/setters.

Getting objects in a JSON response

I have a JSON response which looks like this:
String resp = "{"name":"Renold","age":"16"}"
And I have a POJO named "Person" which contains the attributes 'Name' and 'Age'. How do I extract the attributes from the JSON response and assign them to the POJO? I have already tried GSON and the object gets incorrectly assigned as "Name = name" and "Age = age" instead of the actual response.
Any other suggestions, good lads? :)
EDIT: This is what I used with GSON
Gson gson = new Gson();
final Person p= gson.fromJson(response, Person.class);
This left me with:
p.Name = name;
p.Age = age;
instead of p.Name = Renold.
You can try this with Genson:
String resp = "{"name":"Renold","age":"16"}"
Genson genson = new Genson();
Person person = genson.deserialize(resp, Person.class);
I guess you have to use #SerializedName to map Name to name
check this pojo parse gson with invalid java names
In your Pojo you have to annotate like this.
#SerializedName("name")
private final Name;
Please try serialization using the JObject class using org.json. e.g
JSONObject jsonObj = new JSONObject("{\"name\":\"Renold\",\"age\":\"16"\"}");
Then get the properties:
jsonObj.get("name");
If you're using maven you can include the Jackson dependency. That will map things automagically.
I have used the same scenario you have described and found no issues with your code except the String representation you have used. I have put my code at pastebin. This sample project should resolve your issue of json format.
The string in your response should be:
String response = "{\"name\":\"Renold\",\"age\":16}"

Empty object in browser when returning JSONObject

I have this method :
#GET
#Path("/myservice")
#Produces(MediaType.APPLICATION_JSON)
public Response mysercice() {
boolean userExists = false;
CacheControl cacheControl = new CacheControl();
cacheControl.setNoCache(true);
cacheControl.setNoStore(true);
JSONObject jsonObject = new JSONObject();
jsonObject.put("userExists", userExists);
return Response.ok(jsonObject, MediaType.APPLICATION_JSON).cacheControl(cacheControl).build();
}
When accessing to the URL of the method in the browser, I get { }, it means that the object is empty.
So, I tried to use :
return Response.ok(jsonObject.toString(), MediaType.APPLICATION_JSON).cacheControl(cacheControl).build();
So, I get in the browser {"userExists" : false}
But I didn't understand why when returning simply the JSONObject, we get in the browser an empty object.
Most JAX-RS implementations come with a provider for mapping response entities to JSON. So when you write:
return Response.ok(jsonObject, MediaType.APPLICATION_JSON).build();
You are basically requesting that the JAX-RS provider marshall the JSONObject into JSON for you. The only problem being that JSONObject isn't really meant to be serialized this way. Instead its meant to be used to build a JSON representation incrementally, then convert that representation into a JSON string value. You have two options:
Create a POJO containing all the fields you want to send back to the client. Return this POJO in your method and it will be automatically converted to JSON (`return Response.ok(myPojo, MediaType.APPLICATION_JSON).build()
Return the JSON data directly as a String (which you already did in your example that works).

JSONObject in JSONObject

I have an API Output like this:
{"user" : {"status" : {"stat1" : "54", "stats2" : "87"}}}
I create a simple JSONObject from this API with:
JSONObject json = getJSONfromURL(URL);
After this I can read the data for User like this:
String user = json.getString("user");
But how do I get the Data for stat1 and stat2?
JSONObject provides accessors for a number of different data types, including nested JSONObjects and JSONArrays, using JSONObject.getJSONObject(String), JSONObject.getJSONArray(String).
Given your JSON, you'd need to do something like this:
JSONObject json = getJSONfromURL(URL);
JSONObject user = json.getJSONObject("user");
JSONObject status = user.getJSONObject("status");
int stat1 = status.getInt("stat1");
Note the lack of error handling here: for instance the code assumes the existence of the nested members - you should check for null - and there's no Exception handling.
JSONObject mJsonObject = new JSONObject(response);
JSONObject userJObject = mJsonObject.getJSONObject("user");
JSONObject statusJObject = userJObject.getJSONObject("status");
String stat1 = statusJObject.getInt("stat1");
String stats2 = statusJObject.getInt("stats2");
from your response user and status is Object so for that use getJSONObject and stat1 and stats2 is status object key so for that use getInt() method for getting integer value and use getString() method for getting String value.
To access properties in an JSON you can parse the object using JSON.parse and then acceess the required property like:
var star1 = user.stat1;
Using Google Gson Library...
Google Gson is a simple Java-based library to serialize Java objects to JSON and vice versa. It is an open-source library developed by Google.
// Here I'm getting a status object inside a user object. Because We need two fields in user object itself.
JsonObject statusObject= tireJsonObject.getAsJsonObject("user").getAsJsonObject("status");
// Just checking whether status Object has stat1 or not And Also Handling NullPointerException.
String stat1= statusObject.has("stat1") && !statusObject.get("stat1").isJsonNull() ? statusObject.get("stat1").getAsString(): "";
//
String stat2= statusObject.has("stat2") && !statusObject.get("stat2").isJsonNull() ? statusObject.get("stat2").getAsString(): "";
If You have any doubts , Please let me know in comments ...

Creating JSON objects directly from model classes in Java

I have some model classes like Customer, Product, etc. in my project which have several fields and their setter-getter methods, I need to exchange objects of these classes as a JSONObject via Sockets to and from client and server.
Is there any way I can create JSONObject directly from the object of model class such that fields of the object become keys and values of that model class object become values for this JSONObject.
Example:
Customer c = new Customer();
c.setName("Foo Bar");
c.setCity("Atlantis");
.....
/* More such setters and corresponding getters when I need the values */
.....
And I create JSON Object as:
JSONObject jsonc = new JSONObject(c); //I'll use this only once I'm done setting all values.
Which gets me something like:
{"name":"Foo Bar","city":"Atlantis"...}
Please note that, in some of my model classes, certain properties are itself an object of other model class. Such as:
Product p = new Product();
p.setName("FooBar Cookies");
p.setProductType("Food");
c.setBoughtProduct(p);
In a case like above, as I'd expect, the yielded JSON object would be:
{"name":"Foo Bar","city":"Atlantis","bought":{"productname":"FooBar Cookies","producttype":"food"}}
I know I could create something like toJSONString() in each model class and have the JSON-friendly string created and manipulate it then, but in my previous experiences of creating RESTful service in Java (which is totally out of context for this question), I could return JSON string from the service method by using #Produces(MediaType.APPLICATION_JSON) and have the method returning object of model class. So it produced JSON string, which I could consume at the client end.
I was wondering if it's possible to get similar behavior in current scenario.
Google GSON does this; I've used it on several projects and it's simple and works well. It can do the translation for simple objects with no intervention, but there's a mechanism for customizing the translation (in both directions,) as well.
Gson g = ...;
String jsonString = g.toJson(new Customer());
You can use Gson for that:
Maven dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
Java code:
Customer customer = new Customer();
Product product = new Product();
// Set your values ...
Gson gson = new Gson();
String json = gson.toJson(customer);
Customer deserialized = gson.fromJson(json, Customer.class);
User = new User();
Gson gson = new Gson();
String jsonString = gson.toJson(user);
try {
JSONObject request = new JSONObject(jsonString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Use gson to achieve this. You can use following code to get the json then
Gson gson = new Gson();
String json = gson.toJson(yourObject);
I have used XStream Parser to
Product p = new Product();
p.setName("FooBar Cookies");
p.setProductType("Food");
c.setBoughtProduct(p);
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("p", Product.class);
String jSONMsg=xstream.toXML(product);
System.out.println(xstream.toXML(product));
Which will give you JSON string array.

Categories