robospice parse nested object response - android

I have a JSON object returned by the server like:
{
"success":true,
"value1":1,
"otherValues":{
"var1":1,
"var2":"asd",
"var3":2
}
}
How should I model the response class to accept all the values? For example
package com.phoneme.API.popIndex;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class GetResponse {
private String success
private String value1;
private ??? otherValues;
//GETTERS AND SETTERS of each
}

The response you are trying to decode is not valid JSON. The field names need to be quoted. For example:-
{
"success":true,
"value1":1,
"otherValues":{
"var1":1,
"var2":"asd",
"var3":2
}
}
Using this corrected version of the message, you can generate your POJO here:- http://www.jsonschema2pojo.org/
Good luck!

Related

How to read Response, different from methods used in pojo class from API in Android

I just want to send back an attribute that was not defined in POJO class.
My POJO class is this
public class PostData {
#SerializedName("Token")
#Expose
private String token;
#SerializedName("Amount")
#Expose
private Integer amount;
#SerializedName("AuthID")
#Expose
private String authID;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amt) {
this.amount = amt;
}
public String getAuthID(){return authID;}
public void setAuthID(String authID){
this.authID = authID;
}
}
Amount,Token,AuthID are sent from the client side to API.Here I used HTTP Cloud function as an HTTP POST.I need to send back the TransID to client side which is not there in POJO class.In client side I need to read the response and store it.
Here is my cloud function code:
exports.Add = functions.https.onRequest((req,res)=>{
//var testPublicKey = [xxxxxxxxxxxxxxxxx]
var stripe = require("stripe")("stripe_key");
console.log("Token:"+req.body.Token)
console.log("Amount:"+req.body.Amount)
var tokenToCharge = req.body.Token;
const amountToCharge = req.body.Amount;
var authID = req.body.AuthID;
const databaseRef = admin.firestore();
const payer = databaseRef.collection('deyaPayUsers').doc(authID).collection('Wallet').doc(authID);
const balance = payer.Usd
stripe.charges.create({
amount : amountToCharge,
currency : "usd",
description : "charge created",
source : tokenToCharge,
}, function(err, charge) {
if(charge.status === "succeeded"){
var trans = databaseRef.runTransaction(t=>{
return t.get(payer)
.then(doc=>{
var updatedBalance = doc.data().Usd + parseInt(charge.amount);
t.update(payer,{Usd : updatedBalance});
});//return close
}).then(result=>{
console.log('Transaction success!');
}).catch(err=>{
console.log('Transaction Failure:',err);
});
}
});
});//end of stripe create charge
you add one field in pojo class using transient key is ignore a value to send api call and get client side value.
transient
private String TransID;
and make getter and setter method.
is there any reason why you do not want to create a variable for the TransID in your POJO class? I understand that your POJO class interacts with your Client Side of your application. Hence, having a variable for the TransID(with getters and Setters) will give you more flexibility to read the response and store it as you want.
To read response using Retrofit have a separate class(which is here PostData) that represents the outputs of the JSON response which we get when a request was served by the backend.create an interface class and with #Method(GET, POST, DELETE etc;) annotation and pass parameters to the method.In client-side pass the parameters to the method and get the response by calling the getmethod of the parameter you are expecting.

How can i POST json data in Android

In my application I want POST some data, and this data get users and POST to server. For server requests I use Retrofit2.
For POST this data I should POST with json format, such as this :
{
"email": "example#example.com",
"username": "example",
"password": "123",
}
After POST data I should check with this results for submit data has Ok ro Not.
{
"status": 200,
"Message": "",
"data": true
}
I give Email, Username and Password with EditText from users, but how can I POST this data to server with Json format?
Please help me, I am amateur and I really need this help
Firstly, create a class for your request, for example, LoginRequest.java
public class LoginRequest {
private String email;
private String username;
private String password;
//getters and setters
}
Secondly, create a class for your response, LoginResponse.java
public class LoginResponse {
private Integer status;
private String Message;
private Boolean data;
//getters and setters
}
Finally, in your interface add this method:
public interface MiApiInterface {
#POST("yourResourceName") Call<LoginResponse> login(#Body LoginRequest request);
}
I hope It could help you, just ask me if you have more question.
have you realised that the return of the login method is a Call, it is for a async call, you could use it like this on your activity:
firstly, create a retrofit instance
Retrofit retrofit = ....
Secondly, create your interface instance like this:
MiApiInterface apiInterface = retrofit.create(MiApiInterface.class);
Finally, you could access the login method:
LoginRequest request = new LoginRequest();
request.set();
....
Call<LoginResponse> responseCall = apiInterface.login(request);
responseCall.enqueue(new Callback<LoginResponse>() {
public void onResponse(...){
LoginResponse loginResponse = response.body();
}
public void onFailure(...){
}
}
To Convert Objects to Json automatically, you should add a Converter Factory on your retrofit builder:
Gson gson = new GsonBuilder().create();
Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
...
dont forget import the Gson library on your gradle.
Here is a tutorial on Retrofit 2: http://www.vogella.com/tutorials/Retrofit/article.html
Alternatively, you can use Volley, it is a library specificaly designed to make http requests on Android. https://developer.android.com/training/volley/index.html

Retrofit 2: Handling dynamic JSON response

I am using retrofit 2 as a REST client and I cannot figure out how to deserialise a dynamic JSON response.
Depending on the status value (success or failure), our JSON can have two different objects in the result field:
A successful response returns a User object:
{
"status": 200,
"message": "OK",
"result": {
"id": "1",
"email": "bla#bla.bla"
...
}
}
A failed response returns an Error object:
{
"status": 100,
"message": "FAILED",
"result": {
"error": "a user with this account email address already exists"
}
}
I have created 3 POJO classes...
APIResponse:
public class APIResponse<T> {
#Expose private int status;
#Expose private String message;
#Expose private T result;
...
}
User:
public class User {
#Expose private String id;
#Expose private String email;
...
}
Error:
public class Error {
#Expose private String error;
...
}
Here is how I make the call:
#FormUrlEncoded
#PUT(LOGIN)
Call<APIResponse<User>> login(#Field("email") String email, #Field("password") String password);
And here is how I get a response:
#Override
public void onResponse(Call<APIResponse<User>> call, Response<APIResponse<User>> response) {
...
}
#Override
public void onFailure(Call<APIResponse<User>> call, Throwable t) {
...
}
Question:
The API call expects a return type of Call<APIReponse<User>>. However, it might not get a User object back... So how do I modify this approach to accept either APIResponse<User> or APIResponse<Error>.
In other words, how do I deserialise JSON data that can be in two different formats?
Solutions I have looked at:
Including 'error' field in User class or extending Error class (ugly).
Custom interceptor or converter (struggled to understand).
Convince API devs to change it and make my life easier :)
I am not sure if the solution is viable, but you can try changing <APIResponse<User>> to <APIResponse<Object>>
Call<APIResponse<Object>> login(#Field("email") String email, #Field("password") String password);
#Override
public void onResponse(Call<APIResponse<Object>> call, Response<APIResponse<Object>> response) {
//depending on the response status, you can cast the object to appropriate class
Error e = (Error)response.body().getResult();
//or
User u = (User)response.body().getResult();
}
or another alternative, use String instead of POJO
Call<String> login(#Field("email") String email, #Field("password") String password);
retrieve the JSON and serialize manually or use GSON
You should check the response code and use the desired class to process the json

Retrofit - Can I map response data fields?

I'm testing/creating a REST client to the new Basecamp API using Retrofit. It looks something like this:
class Project {
String name;
String appUrl;
}
interface Basecamp {
#GET("/projects.json")
List<Project> projects();
}
In the json response, the source field for appUrl is called app_url. Asides from renaming the field in the class, is there a simple way to map the response data with my data structure?
So I found the answer in this question. Turns out this can be solved using Gson:
class Project {
String name;
#SerializedName("app_url")
String appUrl;
}
If you are using Jackson for JSON parsing with Retrofit you can use the #JsonProperty annotation:
Example:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
#JsonIgnoreProperties (ignoreUnknown = true)
class Project {
#JsonProperty("name")
String name;
#JsonProperty("app_url")
String appUrl;
}

GSON / JSON converting from innerJsonObject

I need to create the following JSON Object and than convert it to string using the GSON library (toJson(Object)). However, GSON appends the nameValuePair with each JSON Object, what do I need to do?
"Param_1":
{
"SubParam_1": { type: String, required: true }
}
I'm putting these JSONObjects into a ParameterMap (android HTTP Client) and using GSON to convert the map to JSON String.
First of all the JSON "object" you've written is not even valid JSON!
If anything, you could create a JSON like this:
{
"Param_1": {
"SubParam_1": { "type": "String", "required": true }
}
}
And that's very easy, you just need to have the correct class model, something like this:
public class YourClass {
private Param Param_1;
}
public class Param {
private SubParam SubParam_1;
}
public class SubParam {
private String type;
private boolean required;
}
And then you can use the method .toJson(), like this:
Gson gson = new Gson();
String jsonString = gson.toJson(yourObject);

Categories

Resources