how to split data of two object from one JSON response? - android

from server i'm getting json response...but it contais data of two objects..one is of ArrayList Type and 2nd is one POJO(HomeVO) class. i want to split data and store into different objects. i am usnig GSON api.
Servlet:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(questions));
response.getWriter().write(new Gson().toJson(homeVo));
Json Response:
[{"questionId":2,"question":"Quality","typeOfQuestion":2}, {"questionId":3,"question":"Satisfaction","typeOfQuestion":1},{"questionId":4,"question":"overall","typeOfQuestion":2}]{"feedbackName":"IMS","expiryDate":"2014-12-12","createdDate":"2014-10-24","feedbackId":2}
Android Parsing:
HttpClient httpClient = WebServiceUtils.getHttpClient();
try {
HttpResponse response = httpClient.execute(new HttpGet(url));
HttpEntity entity = response.getEntity();
Reader reader = new InputStreamReader(entity.getContent());
data = gson.fromJson(reader, arrayListType);
} catch (Exception e) {
e.printStackTrace();
Log.i("json array",
"While getting server response server generate error. ");
}

You have two choices:
1. Manually parse the strings (What is not recommended)
2. Convert the JSon objects into objects using Gson and then convert it back into one json object also using Gson.
Let me know, if you need more detailed info
More expl.:
Lets say u have two different JSon string, called JsonA and JSonB.
in order to join them, you have to download the Gson library
class AClass{
int idA;
String nameA;
} // Note that the variable's names must be the same as the identifiers in JSON
class BClass{
int idB;
String nameB;
}
class JoinedClass{
BClass bClass;
AClass aClass; //don't forget getters and setters
}
public String joinJson(String JsonA , String JsonB){
Gson gson = new Gson();
AClass aClass = new AClass();
BClass bClass = new BClass();
aClass = gson.fromJson(JsonA, AClass.class);
bClass = gson.fromJson(JsonB, BClass.class);
JoinedClass joinedClass = new JoinedClass();
joinedClass.setAClass(aClass );
joinedClass.setBClass(bClass);
return gson.toJson(joinedClass);
}
// but you know, just after writing this code, i found that there might be an easier way to do this.
// Thanks for attention!

I believe you have two POJO classes for Questions and HomeVO. Then follow these steps:
You can create another DTO with two lists (questions and homeVo).
public class ResultDTO {
private List < HomeVO > homeVoList;
private List < Question > questionList;
//use your getters and setters here:
}
now, use those setters to set your values like you have already done.
then pass that object (ResultDTO) to your gson:
//assuming the ResultDTO object name is resultDto...
response.getWriter().write(new Gson().toJson(resultDto));
now if you check the result in client side, you may have a json response like below:
[questionList: [{
"questionId": 2,
"question": "Quality",
"typeOfQuestion": 2
}, {...}, ],
homeVoList: [{
"feedbackName": "IMS",
"expiryDate": "2014-12-12",
"createdDate": "2014-10-24",
"feedbackId": 2
}, {..}]
so you can get your json objects in response divided like this (this is for web, I dont know how you access it):
//assuming the json reponse is 'data':
var homeVoList = data.homeVoList;
var questionList = data.questionList;
try and see... just a guidance...haven't try actually..

Related

What is the best way to catch the response from server via Retrofit?

What is the best way to cast my response from the server ?
By directly assigning the response to the entity
Ex: authorityStatusWithWorkFlowEntity = response.body();
OR
First Catching it as JsonElement OR JsonArray OR JsonObject and then converting it to specified entity?
Ex: lineEstimationEntity = new Gson().fromJson(response.body().getAsJsonObject(), new TypeToken<LineEstimationEntity>() {
}.getType());
In performance wise which is the best practice?

How to parse JSON response (different object types) with GSON

Problem: parse the following response from Foursquare Venues API:
{
meta: {
code: 200
}
notifications: [
{
type: "notificationTray"
item: {
unreadCount: 0
}
}
]
response: {
venues: [
{
id: "5374fa22498e33ddadb073b3"
name: "venue 1"
},
{
id: "5374fa22498e33ddadb073b4"
name: "venue 2"
}
],
neighborhoods: [ ],
confident: true
}
}
The GSON documentation website recommends using GSON's parse API to parse the response as a JSONArray and then read each array item into an appropriate Object or data type (Example here). As such, I originally switched to the following implementation:
JsonParser parser = new JsonParser();
try {
JSONObject json = new JSONObject(response);
JSONArray venues = json.getJSONObject("response").getJSONArray("venues");
int arraylengh = venues.length();
for(int i=0; i < arraylengh; i++){
Log.d(TAG, "The current element is: " + venues.get(i).toString());
}
}
catch(JSONException e){
}
The code above gave me a JSONArray with all the "venues". The next problem was that I do not know how to parse/convert the "venues" JSONArray into a ArrayList (for my custom Venue object).
Solution: As outlined on JohnUopini answer I was able to successfully parse the JSON by using the following implementation:
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
JsonParser parser = new JsonParser();
JsonObject data = parser.parse(response).getAsJsonObject();
Meta meta = gson.fromJson(data.get("meta"), Meta.class);
Response myResponse = gson.fromJson(data.get("response"), Response.class);
List<Venue> venues = Arrays.asList(myResponse.getVenues());
With the above code I was able to successfully parse the "meta" as well as the "response" JSON properties into my custom objects.
For reference, below is my Response class (NOTE: The properties were defined as public for testing purposes. A final implementation should have these declared as private and use setters/getters for encapsulation):
public class Response {
#SerializedName("venues")
public Venue[] venues;
#SerializedName("confident")
public boolean confident;
Response(){}
}
Note/Feedback: After implementing the accepted answer's recommendation, a couple of times I encountered the following (or similar) exception message during my debugging process:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT
The reason I was getting the above exception was because the "type" on some of the children inside the "venues" JSON did not match with the "type" I defined such objects in my custom Venue class. Make sure the type in your custom Classes has a 1-to-1 correspondence with the JSON (i.e. [ ] is a array property, { } is an Object property, etc).
This is correct because the object you are trying to access is not an array, you should do something like this:
JsonParser parser = new JsonParser();
JsonObject data = parser.parse(response).getAsJsonObject();
Meta meta = gson.fromJson(data.get("meta"), Meta.class);
Response myResponse = gson.fromJson(data.get("response"), Response.class);
Or you can create an object containing 3 classes for the 3 objects and then parse everything through GSON.

parsing json result with generics

I have an app which sends a REST request to a server and receives a JSON response back. However, my REST client service on the app may send out several different types of REST request which will result in different responses causing different types of objects being created on the client android app. Each response will always be an array of some type of object.
Here is what I have so far:
#Override
protected List<?> doInBackground(String... urls) {
requestType = urls[0];
InputStream source = retrieveStream(Constants.REST_SERVER_URL + requestType);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
List<?> result = gson.fromJson(reader, List.class);
return result;
}
protected void onPostExecute(List<?> result) {
if(requestType.equals(Constants.GET_OSM_POI_NODES)) {
Log.v(TAG, String.valueOf(result.size()));
ArrayList<Node> nodes = new ArrayList<Node>();
for(Object o : result) {
// create a node object from the result
}
}
}
In the onPostExecute method I want to create the correct object based on what REST url was used. So for example, if the url corresponding to GET_OSM_POI_NODES was used then it would construct an ArrayList of node objects which consists of a latitude and a longitude along with an id. Here is a sample JSON response for such an object:
[
{
"id": 353941,
"lat": 754030751,
"lon": -39701762
},
...
The problem is that the result passed into onPostExecute is always a List of generic objects because I want it to be generic. I am not sure how to create Node objects from these generic types. Even if I don't use generics the objects passed into onPostExecute are list of StringMap and I don't know how to create different types of object from these.
Any ideas?
Anyone have any idea?
Thanks

What are the best methods to consume a web service from android?

Can anyone tell me which is the best, ease and flexible method to consume web service from android? I'm using eclipse.
Since you only care about consuming a webservice, I assume you already know how to send data from the web server. Do you use JSON or XML, or any other kind of data format?
I myself prefer JSON, especially for Android.
Your question still lacks some vital information.
I personally use apache-mime4j and httpmime-4.0.1 libraries for web services.
With these libraries I use the following code
public void get(String url) {
HttpResponse httpResponse = null;
InputStream _inStream = null;
HttpClient _client = null;
try {
_client = new DefaultHttpClient(_clientConnectionManager, _httpParams);
HttpGet get = new HttpGet(url);
httpResponse = _client.execute(get, _httpContext);
this.setResponseCode(httpResponse.getStatusLine().getStatusCode());
HttpEntity entity = httpResponse.getEntity();
if(entity != null) {
_inStream = entity.getContent();
this.setStringResponse(IOUtility.convertStreamToString(_inStream));
_inStream.close();
Log.i(TAG, getStringResponse());
}
} catch(ClientProtocolException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
_inStream.close();
} catch (Exception ignore) {}
}
}
I make a request via _client.execute([method], [extra optional params])
The result from the request is put in a HttpResponse object.
From this object you can get the status code and the entity containing the result.
From the entity I take the content. The content would in my case be the actualy JSON string. You retrieve this as an InputStream, convert the stream to a string and do whatever you want with it.
For example
JSONArray result = new JSONArray(_webService.getStringResponse()); //getStringResponse is a custom getter/setter to retrieve the string converted from an inputstream in my WebService class.
Depending on how you build your JSON. mine is nested deeply with objects in the array etc.
But handling this is basic looping.
JSONObject objectInResult = result.getJSONObject(count);//count would be decided by a while or for loop for example.
You can extract data from the current JSON object in this case like:
objectInResult.getString("name"); //assume the json object has a key-value pair that has name as a key.
to parse "JSON" I recommend the following library is the faster and better.
Jackson Java JSON-processor

how to pass parameters to RESTlet webservice from android?

I've been looking online for how to pass parameters to RESTlet webservice but it seem there are not much tutorial concerning RESTlet.
I would like to send some parameters gathered from a form on my android application (it would be great if i could do this using JSON).
well i solved this
as for the server side
#Post
public JSONArray serverSideFunction(Representation entity)
throws JSONException {
try {
JSONObject req = (new JsonRepresentation(entity)).getJsonObject();
System.out.println(req.getString(/* filed name */));
System.out.println(req.getString(/* filed name */));
/*
* you can retrieve all the fields here
* and make all necessary actions
*/
} catch (IOException e) {
e.printStackTrace();
}
}
as for the Android Side
HttpClient client = new DefaultHttpClient();
String responseBody;
JSONObject jsonObject = new JSONObject();
try{
HttpPost post = new HttpPost(WebService_URL);
jsonObject.put("field1", ".........");
jsonObject.put("field2", ".........");
StringEntity se = new StringEntity(jsonObject.toString());
post.setEntity(se);
post.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setHeader("Content-type", "application/json");
Log.e("webservice request","executing");
ResponseHandler responseHandler = new BasicResponseHandler();
responseBody = client.execute(post, responseHandler);
/*
* You can work here on your responseBody
* if it's a simple String or XML/JSON response
*/
}
catch (Exception e) {
e.printStackTrace();
}
I hope this may be of help
In fact, it depends on what you want to do. With REST (see http://en.wikipedia.org/wiki/Representational_state_transfer), there are two ways to pass parameters or data. Before you need to understand some concepts:
Resource: the REST entity by itself.
Representation: corresponds to its state and can be gotten or updated using different HTTP methods. The kind of content is identified using the content type header (media type in Restlet).
Methods: the GET method is used to get the resource state, PUT to update it, POST to create a new resource and specify its state the same time, DELETE to delete a resource.
Restlet provides Java entities for REST elements.
So, after described that, you can see that passing data or parameters depends of your use case:
1°) Do you want to update the resource state? In this case, you will use the content of the request with methods like POST or PUT. The data structure is free from text, JSON, XML or binary... Restlet provides the ClientResource class to execute requests on RESTful applications. It also provides support to build the representation to send and extract data from the one received. In this case, your data gathered from a form will be used to build the representation. Here are some samples:
//Samples for POST / PUT
ClientResource cr = new ClientResource("http://...");
cr.post(new StringRepresentation("test"));
MyBean bean = new MyBean();
(...)
//Jackson is a tool for JSON format
JacksonRepresentation<MyBean> repr
= new JacksonRepresentation<MyBean>(bean);
cr.put(repr);
//Samples for GET
Representation repr1 = cr.get();
bean = (new JacksonRepresentation<MyBean>(repr1, MyBean.class)).getObject();
2°) Do you want to specify parameters on your GET requests (for example to configure data to retreive and so on)? In this case, you can simply add it on the ClientResource, as described below:
ClientResource cr = new ClientResource("http://...");
cr.getReference().addQueryParameter("q", "restlet");
Representation repr = cr.get();
In this case, your data gathered from a form will be used to build the parameters.
Hope it helps you.
Thierry
If you want request with json structure and your response as JSONObject maybe you can do like this in server side:
public class RequestJSON extends ServerRecource{
#Post("json")
public JSONObject testRequest(String entity){
JSONObject request = new JSONObject(entity);
String value1 = request.getString("key1");
int value2 = request.getInt("key2");
return /* your JSONObject response */;
}
}
And your request can be :
{"key1":"value1", "key2":value2}
I hope this can help you

Categories

Resources