I have one Registration Api which has error object in which it shows Errors Dynamically in Array.
This is the JsonFormat of Api :
{
"status_code": 422,
"status": "error",
"data": {
"errors": {
"password": [
"The password must be between 8 and 15 characters."
],
"mobile_no": [
"The mobile number has already been taken."
]
}
}
}
Here if a user forgot to write name then it will show username array in errors. So it changes dynamically.
My question is how I can set this type of errors in gson.I am using retrofit to call Api.
I did this in my Data class but it showing me errors.
#SerializedName("errors")
#Expose
JsonObject errorObject;
Iterator iterator=new Iterator() {
#Override
public boolean hasNext() {
Iterator keys=errorObject.keys();
if(keys.hasNext()){
}
}
#Override
public Object next() {
return null;
}
}
Please help me how can I getErrors using gson.Thank u
You can use Map to maintin the datastructure like this:
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(yourErrorsArrayHere, type);
and then just use myMap.get("your_error_key") to get the particular error.
Related
i have a web service for registration. and i have a success response for response code 200 like this
{
"data": {
"email": "azadbar#yahoo.com"
},
"code": 201,
"success": true
}
and i have error response with code 422 like this
{
"message": "The given data was invalid.",
"errors": {
"email": [
"The email has already been taken."
]
}
}
but when also i have problem with password the response error show me like this
{
"message": "The given data was invalid.",
"errors": {
"email": [
"The email must be a valid email address."
],
"password": [
"The password must be at least 6 characters.",
"The password confirmation does not match."
]
}
}
the problem is some field some time show and some time is gone. and also we have some response model and in retrofit interface we should only have One response like RegisterResponse in below sample
#POST("/api/v1/register")
Call<RegisterResponse> register(#Body RegisterRequest request);
how can i handle this response?
You need to create a pojo that means a model class of name RegisterResponse that will have the properties that you are getting in your JSON response. So, according to your example case, it would be like :
Class RegisterResponse{
private Data data;
private String code;
private Boolean success;
private String message;
private Error errors;
}
Class Data{
private String email;
}
Class Error{
private List<String> email;
private List<String> password;
}
Now inside every class, you need to create the getter and setter for every properties that you have included.
So when the response comes then handle it accordingly that mean if it comes null, set the property to null else set the received value for the respective property
You need to make a model with all possible fields and depending on result some will be filled or null.
class Model{
private Data data;
private int code;
private boolean success;
private Errors errors;
private String message;
public isSuccess(){
return success;
}
....
}
When i am getting response success class works perfectly. But when it is fail it gave me error.
Response when fail data pass in URL :
{
"success": -1,
"message": "Invalid username or password",
"data": ""
}
Response when correct data pass in URL:
{
"success": 1,
"message": "User successfully logged in",
"data": {
"userId": 219,
"userName": "mp",
"picture": "219.png",
"isBo": false,
"isPo": true,
"isHm": true,
"hmProfileCompletionStatus": 3,
"poProfileCompletionStatus": 2,
"poPhoto": null,
"hmPhoto": null,
"custStripeToken": "xxx",
"accountStripeToken": "xx",
"bgcStatus": true,
"idCardStatus": true,
"isInsured": null,
"amISponsered": false,
"hmRating": null,
"poRating": null,
"email": "xxx#gmail.com"
}
}
UserResponse.java
#Getter
#Setter
public class UserResponse{
private int success;
private String message;
private User data;
}
Error
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 64 path $.data
It is not possible. In your case it should be like this
{
"success": -1,
"message": "Invalid username or password",
"data": {}
}
Ask your backend service team to change it with an empty object so that the same reponse object can be re used
As per your problem statement you need to make generic type for response .Instead of type User for 'data' object in UserResponse.Class make it Object type like this:-
#Getter
#Setter
public class UserResponseCustom{
private int success;
private String message;
private Object data;// modified for any type of data
}
On webservice call,check whether data is instance of User or not, that's it.
Now you can have a check whether it is object or not
if (userResponseCustom.getData() instanceOf User)
/*userResponseCustom is supposed to be object of UserResponseCustom
which you are getting from server*/
{
// it's an object
// do whatever you want with data as User Object
}
else
{
// it is an string, handle it
}
My Code - I'm trying to return the data from JSON.
JSONObject count = new JSONObject(finalJson);
JSONArray itemsArray = count.getJSONArray("Items");
JSONObject finalObject = itemsArray.getJSONObject(0);
String record = finalObject.getString("myid");
String vocabulary = finalObject.getString("vocab");
String method = finalObject.getString("method");
return record + vocabulary + method;
JSON I'm trying to parse- Count object, Items array, etc...
{
"Count":1,
"Items":[
{
"myid":{
"S":"1"
},
"vocab":{
"S":"print a line"
},
"method":{
"S":"system.out.println"
}
}
],
"ScannedCount":1
If there is a fixed schema, you can transfer the DynamoDB JSON to JSON via a mapping template on API Gateway.
Mapping Template
#set($inputRoot = $input.path('$'))
{
"items": [
#foreach($elem in $inputRoot.Items) {
"myid": "$elem.myid.S",
"vocab": "$elem.vocab.S",
"method": "$elem.method.S"
}#if($foreach.hasNext),#end
#end
]
}
Then, you can parse the JSON String from API Gateway in your Android application into an object.
Sample parsing code
public class Items {
private List<Item> items;
//getters and setters
}
public class Item {
private String myid;
private String vocab;
private String message;
//getters and setters
}
Items items;
ObjectMapper mapper = new ObjectMapper();
jsonData = .... // from API Gateway
items = mapper.readValue(jsonData, Items.class);
Also, there is better way to get those information from API Gateway's generated android SDK. In order to do so, you need to define a Model Schema and set to the method response, then once you deploy your API change this modification, you can download an android SDK for your API.
Model Schema
{
"type": "object",
"properties": {
"items": {
"type": "array",
"item": {
"properties": {
"myid": {
"type": "string"
},
"vocab": {
"type": "string"
},
"method": {
"type": "string"
}
}
}
}
}
}
You might want to read this step by step walkthrough if you want to have more detail on how to mapping response work, and
Is there a way I can get my response to be a single object with an array of users using Eloquent?
For instance:
{
"results" : [
{ "email" : "test1#test.ca" },
{ "email" : "test2#test.ca" }
]
}
Current it outputs like this:
[
{
"email": "test1#test.ca",
},
{
"email": "test2#test.ca",
}
]
This is how I'm displaying users from my code:
$users = User::whereIn('number', $numbers)->select('email')->get();
return $users;
Which would be fine but I'm using Volley for Android using JSONObjectRequest but its failing when it tries to parse the JSON because it can't parse the array.
You can try it like this:
$users = User::whereIn('number', $numbers)->select('email')->get();
return Response::json(array('results' => $users));
I've used gson library for parsing json response. its working well. now i got a problem .
i've got below response from webservice. the json key value is not static, it will dynamically change.
how to write a parser class to parse the below response.
Formatted JSON:
{
"meta": {
"code": 201,
"dataPropertyName": "activity",
"currentTime": "2014-02-05 06:15:04",
"listedCount": "2"
},
"activity": [
{
"comments": [
{
"raja": {
"type": "Liked",
"userPhoto": "663.png",
"userId": "74",
"userName": {
"1_0": "longjump"
},
"postOwner": "you",
"postDetails": {
"471": {
"postImage": "972.png",
"postId": "471",
"postType": "1"
}
},
"dateTime": "2014-02-05 05:24:56",
"sameOwner": "1"
}
}
]
},
{
"follow": [
{
"you": {
"type": "follow",
"followByUserName": {
"0_0": "olivepop",
"1_0": "yadidroy",
"2_0": "chitra"
},
"followUserName": "you",
"followByUserPhoto": "242.png",
"followUserPhoto": "953.png",
"dateTime": "2014-01-09 06:50:42"
}
}
]
}
],
"notifications": [
"Activities has been retrieved successfully"
]
}
Use this parser class
Meta meta = new Meta();
ArrayList<Activity> activity = new ArrayList<ActivityParser.Activity>();
ArrayList<String> notifications = new ArrayList<String>();
public class Meta
{
String code,dataPropertyName,currentTime,listedCount;
}
public class Activity
{
ArrayList<HashMap<String, CommentsItem>> comments = new ArrayList<HashMap<String,CommentsItem>>();
public class CommentsItem
{
String type,userPhoto,userId,postOwner,dateTime,sameOwner;
HashMap<String, String> userName = new HashMap<String,String>();
HashMap<String, PostDetails> postDetails = new HashMap<String,PostDetails>();
public class PostDetails
{
String postImage,postId,postType;
}
}
ArrayList<HashMap<String, FollowItem>> follow = new ArrayList<HashMap<String,FollowItem>>();
public class FollowItem
{
String type,followUserName,followByUserPhoto,followUserPhoto,dateTime;
HashMap<String, String> followByUserName = new HashMap<String,String>();
}
}
If possible get a JSON response with all possible "Key" values and then get the POJO class auto build from below link:
POJO FOR GSON
It will automatically handle all the posibilities. But make sure the RESPONCE you are providing while generating the POJO should hold all the possible combinations of your Key [changing once].
HOPE THIS HELPS!!
Depending on your specification, you can make a Default Webservice response model.java which would be something like:
String success;
#SerializedName("error_msg")
String errorMessage;
#SerializedName("error_code")
String errorCode;
JsonObject data;
where the Parent of the object with dynamic keys would be the "data".
Use Gson, map the model class:
webserviceResponse= gson.fromJson(contentResponse,WebserviceResponse.class);
if (StringUtils.isNotEmpty(webserviceResponse.getSuccess()) &&
StringUtils.equalsIgnoreCase(webserviceResponse.getSuccess(), "success")) {
//check for the dynamic key name
JsonObject job = webserviceResponse.getData();
dynamicallyDefinedKeyClass= gson.fromJson(job.get("dynamicKeyValue"), DynamicallyDefinedKeyClass.class);
}
Will edit my answer on question edit, in any way if it can help
Just a suggestion - raja, you etc. can be values for a key - name or commentsBy ? Where are you getting this response from?