I keep receiving a 400 BAD request when sending a POST request using RestTemplate.
i am sending a list of object and for that i've created a class AllCars witch hase as an field listof Cars this my class:
public class AllCars {
private List<Cars> listcars;
public AllCars() {
}
public AllCars(List<Cars> listcars) {
this.listcars = listcars;
}
public List<Cars> getListcars() {
return listcars;
}
public void setListcars(List<Cars> listcars) {
this.listcars = listcars;
}
}
Cars class
public class Cars {
private Long id;
private long speed;
private String color;
public Cars() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public long getSpeed() {
return speed;
}
public void setSpeed(long speed) {
this.speed = speed;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
this is my client side code:
private class SendData extends AsyncTask<AllCars, Object, AllCars> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(getContext(), "Downloading", "Downloading..Please Wait", true);
}
#Override
protected AllCars doInBackground(AllCars... params) {
try {
// urls
final String urlCars = "http://myurl/addCars";
publishProgress(0);
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson and String message converters
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
AllCars result = restTemplate.postForObject(urlAllCars, params[0], AllCars.class);
return result;
} catch (Exception e) {
Log.e("mainactivity", e.getMessage(), e);
}
return null;
}
#Override
protected void onPostExecute(AllCars ob) {
if(ob instanceof AllCars)
Log.d("AllCars", "success " );
else
Log.d("No Result ", "");
progressDialog.cancel();
}
}
and this is my server side code:
#Requesrmaping (vlaue = "/addCars", method=RequestMethod.POST)
public ResponseEntity<AllCars>addCars(#RequestBody AllCars allcars){
List<Cars> listcar= allcars.getListcars();
return new ResponsEntity<AllCars>(allcars,HttpStatus.ok)
}
this code works when the listcare has one object but when it have more than one object it doesn't work could any body help me
Related
I use Retrofit 2.4 and try to get data from Asp.Net Core 2.0 WebApi Service.
Here Java class:
public class Category {
private int CategoryID;
private String Name;
private String Image;
public Category(){
Name="";
Image="";
}
public Category(int categoryID, String name, String image) {
Name = name;
Image = image;
CategoryID=categoryID;
}
public int getCategoryID() {return CategoryID;}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
}
Here Retrofit code:
public class Common {
public static User CURRENT_USER;
public static String SERVER_NAME="http://ip_address:5000";
public static IApiService ApiService;
public Common()
{
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_NAME)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService = retrofit.create(IApiService.class);
}
}
public interface IApiService
{
#GET("api/Categories")
Call<List<Category>> GetCategoryColl();
}
And then i write server side via Asp.Net Core 2.0 WebApi.
I have a controller:
[Produces("application/json")]
[Route("api/Categories")]
public class CategoriesController : Controller
{
private readonly MovieAppServerContext _context;
public CategoriesController(MovieAppServerContext context)
{
_context = context;
}
// GET: api/Categories
[HttpGet]
public IEnumerable<Category> GetCategory()
{
return _context.Category;
}
// GET: api/Categories/5
[HttpGet("{id}")]
public async Task<IActionResult> GetCategory([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var category = await _context.Category.SingleOrDefaultAsync(m => m.CategoryID == id);
if (category == null)
{
return NotFound();
}
return Ok(category);
}
// PUT: api/Categories/5
[HttpPut("{id}")]
public async Task<IActionResult> PutCategory([FromRoute] int id, [FromBody] Category category)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != category.CategoryID)
{
return BadRequest();
}
_context.Entry(category).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CategoryExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Categories
[HttpPost]
public async Task<IActionResult> PostCategory([FromBody] Category category)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Category.Add(category);
//await _context.SaveChangesAsync();
_context.SaveChanges();
return Ok(category);
}
// DELETE: api/Categories/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteCategory([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var category = await _context.Category.SingleOrDefaultAsync(m => m.CategoryID == id);
if (category == null)
{
return NotFound();
}
_context.Category.Remove(category);
// await _context.SaveChangesAsync();
_context.SaveChanges();
return Ok("Removed!");
}
private bool CategoryExists(int id)
{
return _context.Category.Any(e => e.CategoryID == id);
}
}
Here server side class of Category:
public class Category
{
[Key]
public int CategoryID { get; set; }
public String Name { get; set; }
public String Image { get; set; }
public Category()
{
}
public Category(String name, String image)
{
Name = name;
Image = image;
}
}
So, i check server code via Swagger and it works well: i get all data from Categories List.
But, when i try to get data from Android code via Retrofit - i get collection with empty objects : all fields are null or empty (i think it is default values).
So, here the code:
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
List<Category> _categoryList =new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//some code
Common.ApiService.GetCategoryColl().enqueue(new Callback<List<Category>>() {
#Override
public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
Log.i("GetCategories",response.message());
_categoryList=response.body();
// !!!! HERE. _category list contains objects but all of them
// are empty!
}
#Override
public void onFailure(Call<List<Category>> call, Throwable t) {
Log.e("GetCategories",t.getMessage());
}
});
}
}
So, i do not know, why it happens? How to fix that?
Thank you!
You haven't added #SerializedName("json-key-name") to your fields in the Java Category class:
#SerializedName("categoryId")
private int CategoryID;
#SerializedName("name")
private String Name;
#SerializedName("image")
private String Image;
Now GSON can map JSON response to the POJO properly.
By default Gson expects the field names to be the same as the Json ones, if you want to change this behavior, you have two options:
1.Use a FieldNamingPolicy, for your case it would be UPPER_CAMEL_CASE, below a sample how to do it for Retrofit:
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVER_NAME)
.addConverterFactory(GsonConverterFactory.create())
.build();
2. Use the SerializedName annotation on your java fields.
Here is the intentservice where I get error in logout
public class intentService extends IntentService {
#Override
protected void onHandleIntent(Intent intent) {
RequestQueue queue = MyVolley.getRequestQueue(this);
queue = MyVolley.getRequestQueue(this);
GsonRequest<Routes> gsonRequest = new GsonRequest<Routes>(
url_routes + key, Routes.class, null, createMyReqSuccessListenerRoutes(key),
createMyReqErrorListenerRoutes());
queue.add(gsonRequest);
Function for receive in intentservice
private Response.Listener<Routes> createMyReqSuccessListenerRoutes(final int key) {
return new Response.Listener<Routes>() {
#SuppressLint("LongLogTag")
#Override
public void onResponse(Routes response) {
if (ds.checkTable(DataBaseHelper.TABLE_NAME_TRANSPORT)) {
ds.createTableRoute();
final int size = response.getResults().size();
if (size > 0) {
final int part = 100 / size;
int i;
for (i = 0; i < size; i++) {
ds.insertRoutes(DataBaseHelper.TABLE_NAME_ROUTE,
response.getResults().get(i).getRoute(),
response.getResults().get(i).getStop_id(),
response.getResults().get(i).getNum(),
response.getResults().get(i).getLat(),
response.getResults().get(i).getLon(),
response.getResults().get(i).getRadius(),
response.getResults().get(i).getAudio(),
response.getResults().get(i).getEnd(),
response.getResults().get(i).getMove_time(),
response.getResults().get(i).getStop_time(),
response.getResults().get(i).getPlayonce(),
response.getResults().get(i).getName(),
key
);
}
}
}
}
}
}
Call it from another activity
serviceintentRoute = new Intent(DataBase.this, intentService.class);
startService(serviceintentRoute.putExtra("key", idp));
My RouteData class
public class RoutesData {
private Integer route;
private Integer stop_id;
private Integer num;
private String name;
private String lat;
private String lon;
private Integer radius;
private String audio;
private Integer stop_time;
private Integer move_time;
private Integer end;
private Integer trid;
public RoutesData() {
}
public Integer getRoute() {
return route;
}
public void setRoute(Integer route) {
this.route = route;
}
public Integer getStop_id() {
return stop_id;
}
public void setStop_id(Integer stop_id) {
this.stop_id = stop_id;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public Integer getRadius() {
return radius;
}
public void setRadius(Integer radius) {
this.radius = radius;
}
public String getAudio() {
return audio;
}
public void setAudio(String audio) {
this.audio = audio;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
public Integer getEnd() {
return end;
}
public void setEnd(Integer end) {
this.end = end;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getTrid() {
return trid;
}
public void setTrid(Integer trid) {
this.trid = trid;
}
public Integer getStop_time() {
return stop_time;
}
public void setStop_time(Integer stop_time) {
this.stop_time = stop_time;
}
public Integer getMove_time() {
return move_time;
}
public void setMove_time(Integer move_time) {
this.move_time = move_time;
}
}
And Routes
public class Routes {
public ArrayList<RoutesData> data;
public Routes(ArrayList<RoutesData> data) {
this.data = data;
}
#Override
public String toString() {
return "Response [results=" + data + "]";
}
public ArrayList<RoutesData> getResults() {
return data;
}
}
Class MyVolley
public class MyVolley {
private static RequestQueue mRequestQueue;
private Context context;
public MyVolley() {
}
static void init(Context context) {
mRequestQueue = Volley.newRequestQueue(context);
int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
.getMemoryClass();
// Use 1/8th of the available memory for this memory cache.
int cacheSize = 1024 * 1024 * memClass / 8;
// mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(cacheSize));
}
public static RequestQueue getRequestQueue(Context mContext) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mContext);
}
return mRequestQueue;
}
}
class gsonrequest
public class GsonRequest<T> extends Request<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Response.Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param clazz Relevant class object, for Gson's reflection
* #param headers Map of request headers
*/
public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
Log.d("Response.success", json.toString());
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
I don`t know how to receive all data
Logcat output in Android Studio
The logout
D/Response.success: {"status":true,"data"
:[{"route":1,"num":1,"stop_id":30,"name":"\u043f\u043b.......etc..
not full the line, the next line I had the error
D/ERRORĀ RESPONSE: ERROR RESPONSE Routes
If I understand right the memory is not enough for all array of json massive
I had tried to increase it via
int cacheSize = 2048 * 2048 * memClass / 8;
but not luck
I had to receive all massive not devided it
Sorry for my formatted code
In Daata function try to fetch data from server. Successfully fetched, but data cant be set in ArrayList
List<FlowerListModel>flowerListModels=new ArrayList<>();
Cause i want to set flowerListModels data in FlowerAdapter and show in listview
public void Daata() {
Call<List<FlowerListData>>listCall=apiInterface.getflowers();
listCall.enqueue(new Callback<List<FlowerListData>>() {
#Override
public void onResponse(Call<List<FlowerListData>> call, Response<List<FlowerListData>> response) {
Log.d("DataCheck",new Gson().toJson(response.body()));
List<FlowerListModel>flowerListModels=new ArrayList<>();
FlowerAdapter flowerAdapter = new FlowerAdapter(getApplicationContext(),flowerListModels);
listView.setAdapter(flowerAdapter);
}
#Override
public void onFailure(Call<List<FlowerListData>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
}
});
}
Here is FlowerListModel class
package bdservers.com.schoolmanagement.Model;
public class FlowerListModel {
private String category;
private String instructions;
private String photo;
private String name;
private String price;
public FlowerListModel(){}
public FlowerListModel(String category, String instructions, String photo, String name,String price){
this.category=category;
this.instructions=instructions;
this.photo=photo;
this.name=name;
this.price=price;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getInstructions() {
return instructions;
}
public void setInstructions(String instructions) {
this.instructions = instructions;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
You are setting empty ArrayList to your adapter, I have highlighted the line where you have made the error, and also the correct line that you need
public void Daata() {
Call<List<FlowerListData>>listCall=apiInterface.getflowers();
listCall.enqueue(new Callback<List<FlowerListData>>() {
#Override
public void onResponse(Call<List<FlowerListData>> call, Response<List<FlowerListData>> response) {
Log.d("DataCheck",new Gson().toJson(response.body()));
/**
* You are setting this empty list to adapter
*List<FlowerListModel>flowerListModels=new ArrayList<>();
*/
List<FlowerListModel> flowerListModels = new ArrayList<>();
flowerListModels = response.body();
FlowerAdapter flowerAdapter = new FlowerAdapter(getApplicationContext(),flowerListModels);
listView.setAdapter(flowerAdapter);
}
#Override
public void onFailure(Call<List<FlowerListData>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
}
});
}
You are creating new empty List here: List<FlowerListModel>flowerListModels=new ArrayList<>();
You can try something like this:
#Override
public void onResponse(Call<List<FlowerListData>> call, Response<List<FlowerListData>> response) {
Log.d("DataCheck",new Gson().toJson(response.body()));
FlowerAdapter flowerAdapter = new FlowerAdapter(getApplicationContext(),response.body());
listView.setAdapter(flowerAdapter);
}
Create BaseResponse model like this
public class BaseResponse {
#SerializedName("data")
private List<Object> alObjects;
public BaseResponse(List<Object> alObjects) {
this.alObjects = alObjects;
}
public List<Object> getAlObjects() {
return alObjects;
}
public void setAlObjects(List<Object> alObjects) {
this.alObjects = alObjects;
}
}
Then get data from server
#POST(Constants.URL_API_DATA)
BaseResponse executeBaseResponse(#Body String mData);
Cheers!!
I'm new to Retrofit and JSON and I don't really know how to parse the next json string:
{
"weight":[
{ "bmi":21,
"date":"2016-12-09",
"fat":14.059000015258789,
"logId":1222222222222,
"source":"Aria",
"time":"11:58:24",
"weight":68
},
{ "bmi":21.83,
"date":"2016-12-14",
"logId":1222222222223,
"source":"Aria",
"time":"14:31:39",
"weight":70.7
}
]
}
I just want "weight" and "date" inside weight array. I've created a pojo class following some examples but it's not working.
Also when trying it with my pojo class I couldn't get "weight" as a string (I'll then use it as a double) using .string().
(I know using .toString() shows something like "com.myPackage.MyPojo#xxxx").
For now, I have only been able to get the whole json through ResponseBody:
Call<ResponseBody>call = repository.getFitbitApi().getData();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
What am I doing wrong? Here are my pojo classes, just an attempt...:
public class WeightList {
#SerializedName("weight")
#Expose
private ArrayList<WeightLogFitbit> weight = new ArrayList<>();
public WeightList(){
}
public ArrayList<WeightLogFitbit> getWeight() {
return weight;
}
public void setWeight(ArrayList<WeightLogFitbit> weight) {
this.weight = weight;
}
}
And:
public class WeightLogFitbit {
//Variables in my JSON
#SerializedName("bmi")
#Expose
private String bmi;
#SerializedName("date")
#Expose
private String date;
#SerializedName("logId")
#Expose
private String logId;
#SerializedName("source")
#Expose
private String source;
#SerializedName("time")
#Expose
private String time;
#SerializedName("weight")
#Expose
private double weight;
#SerializedName("fat")
#Expose
private String fat;
public WeightLogFitbit(){}
//Getters and setters
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getBmi(){
return bmi;
}
public void setBmi(String bmi) {
this.bmi = bmi;
}
//
public String getFat(){
return fat;
}
public void setFat(String fat) {
this.fat = fat;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getLogId() {
return logId;
}
public void setLogId(String logId) {
this.logId = logId;
}
}
NOTE: I'm using RxSocialConnect library, which implements RxJava, Retrofit 2, OkHttp3 and gson, just in case. I did this following this example.
Rest of classes I'm using:
public class FitbitBtnActivity extends AppCompatActivity {
private FitbitRepository repository;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fitbit_btn);
repository = new FitbitRepository();
setUpFitbit();
}
private void setUpFitbit() {
findViewById(R.id.fitbitbtn).setOnClickListener(v ->
RxSocialConnect.with(this, repository.fitbitService())
.subscribe(response -> response.targetUI().showToken(response.token()),
error -> showError(error))
);
findViewById(R.id.retrievebtn).setOnClickListener(v -> {
Call<ResponseBody>call = repository.getFitbitApi().getData();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
//Original code from example in RxSocialConnect
/*.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Object>() {
#Override
public void call(Object user) {
FitbitBtnActivity.this.showUserProfile(user.toString());
}
},
error -> FitbitBtnActivity.this.showError(error));*/
}
);
}
And:
public class FitbitRepository {
private final FitbitApiRest fitbitApi;
public FitbitRepository() {
fitbitApi = initFitbitApiRest();
}
private FitbitApiRest initFitbitApiRest() {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new OAuth2Interceptor(FitbitApi20.class))
.build();
return new Retrofit.Builder()
.baseUrl(FitbitApiRest.URL_BASE)
.client(client)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build().create(FitbitApiRest.class);
}
FitbitApiRest getFitbitApi() {
return fitbitApi;
}
interface FitbitApiRest {
String URL_BASE = "https://api.fitbit.com";
#GET("myrequest.json")
Call<ResponseBody> getData();
}
OAuth20Service fitbitService() {
final String client_id = "xxxxx";
final String client_secret = "1xxxxxxxxxxxxxxxxxx";
final String redirect_uri = "http://example.com";
final String permissions = "weight";
return new ServiceBuilder()
.apiKey(client_id)
.apiSecret(client_secret)
.callback(redirect_uri)
.scope(permissions)
.build(FitbitApi20.instance());
}
}
You need to add this to your dependencies:
compile 'com.squareup.retrofit2:converter-gson:your-version'
and then add a gson converter to your Retrofit instance like this:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
and change your call in the api to return WeightList:
Call<WeightList> getData();
I have this json string to parse {"uid":8,"totalPoints":"7740"}
I have written the below class for this.
public class Points extends WebRequest implements IWebRequest {
private static final String CLASS_TAG = Points.class.getSimpleName();
private WebAPIResponse mWebAPIResponse;
private int mUserId;
/**
* Initialize object
* #param urlEndPoint
* #param uiDelegate
* #param appContext
* #param webServiceRequestCallback
*/
public Points(String urlEndPoint, IUIDelegate uiDelegate,
WeakReference<Context> appContext,
IWebServiceRequestCallback webServiceRequestCallback) {
super(urlEndPoint, uiDelegate, appContext, webServiceRequestCallback);
}
#Override
public String parseResponse(String responseString) {
if (MBUtil.isEmpty(responseString)) {
return "";
}
String errMsg = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
WebAPIResponse webAPIResponse = objectMapper.readValue(responseString, WebAPIResponse.class);
this.mWebAPIResponse = webAPIResponse;
Errors errors = webAPIResponse.getErrors();
if (errors != null) {
errMsg = errors.getMsg();
}
} catch (Exception e) {
Log.e(CLASS_TAG, e.getMessage());
errMsg = e.getMessage();
}
return errMsg;
}
#Override
public JSONObject buildRequestBody() {
JSONObject jsonObject = new JSONObject();
Context context = getAppContext();
if(context == null) {
return jsonObject;
}
try {
// Authentication body parameters
JSONObject authenticationJsonObject = new JSONObject();
authenticationJsonObject.put(context.getString(R.string.key_points_uid), mUserId);
return authenticationJsonObject;
} catch (Exception e) {
Log.e(CLASS_TAG, e.getMessage());
}
return jsonObject;
}
public int getUserId() {
return mUserId;
}
public void setUserId(int mUserId) {
this.mUserId = mUserId;
}
public WebAPIResponse getWebAPIResponse() {
return mWebAPIResponse;
}
public void setWebAPIResponse(WebAPIResponse mWebAPIResponse) {
this.mWebAPIResponse = mWebAPIResponse;
}
public static class WebAPIResponse {
private Data pointsData;
private Errors errors;
public Data getPointsData() {
return pointsData;
}
public void setPointsData(Data pointsData) {
this.pointsData = pointsData;
}
public Errors getErrors() {
return errors;
}
public void setErrors(Errors errors) {
this.errors = errors;
}
}
public static class Data {
#JsonProperty("uid")
private int uid;
#JsonProperty("totalPoints")
private int totalPoints;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public int getTotalPoints() {
return totalPoints;
}
public void setTotalPoints(int totalPoints) {
this.totalPoints = totalPoints;
}
}
}
I getting proper response in parseResponse() method which is,
responseString = {"uid":8,"totalPoints":"7740"}
But in the same pasreResponse() method once it reached to this line
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
WebAPIResponse webAPIResponse = objectMapper.readValue(responseString, WebAPIResponse.class);
Not responding any thing and unable to parse the string. Please anyone check whether my parsing class is correct or not and why it is not parsing.
With your responseString = {"uid":8,"totalPoints":"7740"} you just can deserialize it by Data object only.
Data data = objectMapper.readValue(responseString, Data.class);
If you want to deserialize your JSON String to WebAPIResponse object, your responseString must be:
{"pointsData":{"uid":8,"totalPoints":"7740"}, "errors": ...}