This is my Request which i need to send in #Post request with Data as a key. Please help me, I am stuck since 2 days.
[
{
"barcodeList": "abc",
"fieldboyId": "17",
"lattitude": "37.4219513",
"longitude": "-122.0841169",
"quantity": "2",
"refrenceId": "1",
"sampleId": null,
"sampleName": null,
"sampleType": null,
"type": "Barcode"
},
{
"barcodeList": "acd",
"fieldboyId": "17",
"lattitude": "37.4219513",
"longitude": "-122.0841169",
"quantity": "1",
"refrenceId": "1",
"sampleId": null,
"sampleName": null,
"sampleType": null,
"type": "Barcode"
}
]
You could make these classes:
public class RequestBody {
List<Data> data;
public class Data {
String barcodeList;
String fieldboyId;
String lattitude;
String longitude;
String quantity;
String refrenceId;
String sampleId;
String sampleName;
String sampleType;
String type;
}
}
and in the interface something like
#POST("/api/path")
Call<Something> myPostRequest(#Body requestBody: RequestBody);
Related
How to parse a Json with a field "data" which can contain several types of objets, or an object and a simple message (outside the object structure).
An Android app request information to its backend. In most cases, the response has the same structure and if the "data" field only contains one kind of object i can complete the process.
But if the "data" field contains several kinds of objects or one object with a external message, i can´t parse it.
Normal Response structure (I can parse these cases):
{
"success": true,
"code": "OK",
"error": null,
"data": {
"_type": "auth",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImlzcyI6Im9mZnRpbWUiLCJzdWIiOiJkZXZlbG9wZXIifQ==.eyJyb2xlIjpbImFwcCJdLCgfgdfgJhcgdfgdfAiOiJPRkZUSU1FIEFuZHJvaWQiLCJvd25lcdsgsghhjghkukI6Ik9zY2FyIn0=.7PiMEmX8M3ABs7P8KymuXvBpTL1gdgdfLRajFbwxP5IBARM=",
"refresh": null,
"logout": null
}
}
Response with an object "user" and a message (i have problems parsing it):
{
"success": true,
"code": "USER_ALREADY_EXISTS",
"error": null,
"data": {
"user": {
"_type": "user",
"id": 32,
"name": "Pascual22",
"email": "pascual22#juanedc.com",
"picture": null
},
"message": "This email is already registered, you will receive an email with the reset password instructions"
}
}
Response with several kinds of objects (i have problems parsing it):
{
"success": true,
"code": "O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lZ5SWl3aVpYaHdJam94TlRZd05UazJNelV3ZlE9PS5leUp5YjJ4bElqcGJJbUZ3Y0NJc0luVnpaWElpWFN3aWIzZHVaWElpT2pJMkxDSmtaWFpwWTJVaU9pSTVJbjA9Lkp4YmlkcUNuWk5DdDhleVJVYkxFOEhFSktlV2d3RmVqelwvOXJNSlBvS1MwPSJ9.syuKoi8XiHp/me/AJAydyXfRbXa63KVWqPSKS7ySGQc="
},
"user": {
"_type": "user",
"id": 26,
"name": "Sin Foto 2",
"email": "sf2#yopmail.com",
"picture": null
},
"device": {
"_type": "device",
"id": "9",
"category": "mobile",
"manufacturer": "Xiaomi",
"model": "Mi A1",
"os": "android",
"os_version": "9",
"sim_support": true,
"name": null,
"added": "2019-06-10 10:59:10"
}
}
}
My class response:
#JsonIgnoreProperties(ignoreUnknown = true)
public class Response {
#JsonProperty("success")
private String success;
#JsonProperty("code")
private String code;
#JsonProperty("error")
private String error;
#JsonProperty("data")
private Object data;
public String getSuccess() {return success;}
public void setSuccess(String success) {this.success = success;}
public String getCode() {return code;}
public void setCode(String code) {this.code = code;}
public String getError() {return error;}
public void setError(String error) {this.error = error;}
public Object getData() {return data;}
public void setData(Object data) {this.data = data;}
}
Initial parsing process (from Json to Response Object, using spring for android framework, ):
responseApi = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, Response.class);
Parsing Process of data field to Objects (Example with a user object in "data"):
try {
User user = mapper.convertValue(responseApi.getBody().getData(), User.class);
}
catch (Exception e){
e.printStackTrace();
}
I tried to make a Data class with a generic object and a message atributes, but, it din´t work. I need to parse the response in all cases, how can i achieve it? Some suggestions about the class structure in order to make a correct automatic parsing process?
How can I parse JSON using GSON with variable object names? The "routes" objects has the same structure, but different name. It has many different names because it reflects to travel lines. I'm trying to read it directly to Java class (Android, Retrofit), but I wouldn't create single class for all travel lines in Budapest. Is it possible to read it somehow?
{
"version": 2,
"status": "OK",
"code": 200,
"text": "OK",
"currentTime": 1448881433747,
"data": {
"limitExceeded": false,
"references": {
"routes": {
"BKK_9630": {
"id": "BKK_9630",
"shortName": "963",
"longName": null,
"description": "Hűvösvölgy | Nagykovácsi, Tisza István tér",
"type": "BUS",
"url": null,
"color": "1E1E1E",
"textColor": "FFFFFF",
"agencyId": "BKK",
"bikesAllowed": false
},
"BKK_0630": {
"id": "BKK_0630",
"shortName": "63",
"longName": null,
"description": "Hűvösvölgy | Nagykovácsi, Tisza István tér",
"type": "BUS",
"url": null,
"color": "009FE3",
"textColor": "FFFFFF",
"agencyId": "BKK",
"bikesAllowed": false
}
},
"trips": {},
"alerts": {}
}
}
}
The full JSON response:
http://futar.bkk.hu/bkk-utvonaltervezo-api/ws/otp/api/where/search.json?query=Erd%C3%A9szh%C3%A1z
Thanks in advance!
Here's your class structure:
MyObject (main object):
public class MyObject{
private Integer version;
private String status;
private Integer code;
private Data data;
}
Data:
public class Data{
private boolean limitExceeded;
private References references;
}
References:
public class References{
private Map<String, Route> routes;
}
Route:
public class Route{
private String shortName;
}
And then:
String json = "{'version':2,'status':'OK','code':200,'text':'OK','currentTime':1448881433747,'data':{'limitExceeded':false,'references':{'routes':{'BKK_9630':{'id':'BKK_9630','shortName':'963','longName':null,'description':'Hűvösvölgy | Nagykovácsi, Tisza István tér','type':'BUS','url':null,'color':'1E1E1E','textColor':'FFFFFF','agencyId':'BKK','bikesAllowed':false},'BKK_0630':{'id':'BKK_0630','shortName':'63','longName':null,'description':'Hűvösvölgy | Nagykovácsi, Tisza István tér','type':'BUS','url':null,'color':'009FE3','textColor':'FFFFFF','agencyId':'BKK','bikesAllowed':false}},'trips':{},'alerts':{}}}}";
Gson gson = new Gson();
MyObject fromJson = gson.fromJson( json, MyObject.class );
System.out.println( fromJson );
Result:
MyObject [version=2, status=OK, code=200, data=Data [limitExceeded=false, references=References [routes={BKK_9630=Route [shortName=963], BKK_0630=Route [shortName=63]}]]]
Note that, I didn't write all fields you have to write them. Also don't forget to create getter and setters and toString overrides.
I have watched more than 5 hours YouTube tutorials but im simply dont getting how to make this work. There is always something that I dont understand or that with me doesnt work.!
I want to get data from Database and bring it to my Android. I have read this might work with JSON.
Here is the link to my JSON DB export. Is this correct?
http://web2page.ch/apps/FruityNumber/recordShow2.php
The API I use:
compileSdkVersion 23
I'm hoping you could help me out step by step. I'm looking for the simplest way.
There are several ways to perform this. You can perform a Http request to the server and fetch the results, parse them manually into java objects. Or use a library like Gson that would save you the work to parse manually and serialize the JSON string to java objects.
But what I would recommend is using Retrofit an Http client that would let you easily download the JSON data and parse it into a POJO (Plain Old Java Object). Retrofit uses coverters for this purpose like Gson, Jackson, Moshi etc.
Using Retrofit is fairly simple,
Define an interface (Synchronous or Asynchronous) and define API end-points
Build a Retrofit object with the Base URL
If performing a synchronous request, retrofit will generate an implementation for your interface and you will have to make sure that you make the request in a background thread
If performing asynchronous request, you will need to register a call back through which you will get the response
Finally a POJO class for your response,
public class Item {
public String id;
public String user;
public String highscore;
}
Here is a complete guide on how to use Retrofit.
It would be easier to use a library like GSON to convert JSON to Java objects.
The way it works you create a model class for example:
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
#Generated("org.jsonschema2pojo")
public class Result{
#SerializedName("id")
#Expose
private String id;
#SerializedName("user")
#Expose
private String user;
#SerializedName("highscore")
#Expose
private String highscore;
/**
*
* #return
* The id
*/
public String getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(String id) {
this.id = id;
}
/**
*
* #return
* The user
*/
public String getUser() {
return user;
}
/**
*
* #param user
* The user
*/
public void setUser(String user) {
this.user = user;
}
/**
*
* #return
* The highscore
*/
public String getHighscore() {
return highscore;
}
/**
*
* #param highscore
* The highscore
*/
public void setHighscore(String highscore) {
this.highscore = highscore;
}
}
This is makes it very easy:
Gson gson = new Gson();
List<Result> results = gson.fromJson(json, new TypeToken<List<Result>>(){}.getType());
Example:
for(Result res : results){
Log.d(LOG_TAG, "id = " + res.getId());
}
There are many ways to get your work done. But I am going with simple one.
First of all bring all json data from server side to client side(means app side) by making HTTP request. You can do using android preferred HttpUrlConnection Class. You can visit here for doing this.
http://syntx.io/how-to-send-an-http-request-from-android-using-httpurlconnection/
Once you have brought your data on app side. You have to parse that json format data using JSONObject and JSONArray class.For that you have to make a model class.For doing this, you can visit
http://androidexample.com/JSON_Parsing_-_Android_Example/index.php?view=article_discription&aid=71&aaid=95
I think you should change your json format like this:
{
"Results": [
{
"id": "1",
"user": "ero",
"highscore": "13 Sek"
},
{
"id": "2",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "3",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "4",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "5",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "6",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "7",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "8",
"user": "rick",
"highscore": "21 Sek"
},
{
"id": "9",
"user": "",
"highscore": ""
},
{
"id": "10",
"user": "Stefano",
"highscore": "alle"
},
{
"id": "11",
"user": "Test001",
"highscore": "Test001"
},
{
"id": "12",
"user": "",
"highscore": ""
},
{
"id": "13",
"user": "Stefano",
"highscore": "5sek"
},
{
"id": "14",
"user": "sven",
"highscore": "1"
},
{
"id": "15",
"user": "sven",
"highscore": "1"
},
{
"id": "16",
"user": "sven",
"highscore": "1"
},
{
"id": "17",
"user": "",
"highscore": ""
},
{
"id": "18",
"user": "kiala",
"highscore": ""
},
{
"id": "19",
"user": "kiala",
"highscore": "angola"
},
{
"id": "20",
"user": "kiala",
"highscore": ""
}
]
}
It looks pretty relevant and easy to parse. For changing your json format, you can code in your php file.
$sql = mysqli_query("SELECT ...");
$resluts = array();
while($row = mysqli_fetch_assoc($sql)) {
$tmp = array();
$tmp["id"] = $row["id"];
$tmp["user"] = $row["user"];
$tmp["highscore"] = $row["highscore"];
array_push($results["Results"], $tmp);
}
echo json_encode($results);
I am integrating Stripe Payment module in my application. In that I use this Stripe Library.
Now using this code I generating token. Using this token I need card id before payment.
How to get this card id'. ?
Here I show you response of Stripe.
When I enter Card Information about the card Like this :
Stripe_Token::create(array(
"card" => array(
"number" => "4242424242424242",
"exp_month" => 8,
"exp_year" => 2015,
"cvc" => "314"
)
));
After that Stripe give me this response :
{
"id": "tok_14WdJ02eZvKYlo2CyaZ49ZP7",
"livemode": false,
"created": 1409272314,
"used": false,
"object": "token",
"type": "card",
"card": {
"id": "card_14WdJ02eZvKYlo2C5nE5XjtP",
"object": "card",
"last4": "4242",
"brand": "Visa",
"funding": "credit",
"exp_month": 8,
"exp_year": 2015,
"fingerprint": "Xt5EWLLDS7FJjR1c",
"country": "US",
"name": null,
"address_line1": null,
"address_line2": null,
"address_city": null,
"address_state": null,
"address_zip": null,
"address_country": null,
"customer": null
}
}
Before payment and after token created
I need this card id :
"card": {
"id": "card_14WdJ02eZvKYlo2C5nE5XjtP",
}
Hope you get my question.
As you can see in the response from stripe, you can simple get your card id and all other fields from the token object you get in response as follows:
String card_id = token.getCard().getId(); // to get card id
String id = token.getId(); // to get this "id": "tok_14WdJ02eZvKYlo2CyaZ49ZP7"
boolean live_mode = token.getLivemode(); // to get livemode
String last_four = token.getCard().getLast4(); // to get last 4
where token is the response object.
After Generating token
Use this...
Customer.all(new HashMap<String, Object>());
Using this finally i got Cardid which i want.
Here is the total response of Customer.
{
"data": [
com.stripe.model.Customer JSON: {
"object": "customer",
"created": 1410001523,
"id": "cus_4j9JlwfZ5arO4M",
"livemode": false,
"description": null,
"email": "customer#example.com",
"delinquent": false,
"metadata": {
},
"subscriptions": {
"object": "list",
"total_count": 0,
"has_more": false,
"url": "/v1/customers/cus_4j9JlwfZ5arO4M/subscriptions",
"data": [
]
},
"discount": null,
"account_balance": 0,
"currency": "usd",
"cards": {
"object": "list",
"total_count": 1,
"has_more": false,
"url": "/v1/customers/cus_4j9JlwfZ5arO4M/cards",
"data": [
{
"id": "card_14Zh0M2eZvKYlo2CAl9gQ262",
"object": "card",
"last4": "4242",
"brand": "Visa",
"funding": "credit",
"exp_month": 12,
"exp_year": 2015,
"fingerprint": "Xt5EWLLDS7FJjR1c",
"country": "US",
"name": "akinci_yasin#hotmail.com",
"address_line1": null,
"address_line2": null,
"address_city": null,
"address_state": null,
"address_zip": null,
"address_country": null,
"cvc_check": null,
"address_line1_check": null,
"address_zip_check": null,
"customer": "cus_4j9JlwfZ5arO4M"
}
]
},
"default_card": "card_14Zh0M2eZvKYlo2CAl9gQ262"
},
#<com.stripe.model.Customer[...] ...>,
#<com.stripe.model.Customer[...] ...>
],
"has_more": false
}
Hope it may help for You.
Thanks
Using gson:
package gson.sample.one;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class gsonsample
{
public class card {
public String id;
public String object;
public String last4;
public String brand;
public String funding;
public int exp_month;
public int exp_year;
public String fingerprint;
public String country;
public String name;
public String address_line1;
public String address_line2;
public String address_city;
public String address_state;
public String address_zip;
public String address_country;
public String customer;
}
public class Response {
public String id;
public Boolean livemode;
public int created;
public String object;
public String type;
public card card;
}
public static void main(String [] args)
{
String json = "{ \"id\": \"tok_14WdJ02eZvKYlo2CyaZ49ZP7\", \"livemode\": false, \"created\": 1409272314, \"used\": false, \"object\": \"token\", \"type\": \"card\", \"card\": { \"id\": \"card_14WdJ02eZvKYlo2C5nE5XjtP\", \"object\": \"card\", \"last4\": \"4242\", \"brand\": \"Visa\", \"funding\": \"credit\", \"exp_month\": 8, \"exp_year\": 2015, \"fingerprint\": \"Xt5EWLLDS7FJjR1c\", \"country\": \"US\", \"name\": null, \"address_line1\": null, \"address_line2\": null, \"address_city\": null, \"address_state\": null, \"address_zip\": null, \"address_country\": null, \"customer\": null } }";
//
Gson gson = new GsonBuilder().create();
Response response = gson.fromJson(json, Response.class);
String id = response.card.id;
System.out.println(id);
}
}
Stripe also has these objects defined in the model definitions of their Java API and usage examples in their unit tests.
Can somebody help me with Gson parser. When I remove change from JSON and Result it works fine but with change it throws JsonParseException-Parse failed.
Result[] response = gson.fromJson(fileData.toString(), Result[].class);
I have classes like this
public class Result {
public String start_time;
public String end_time;
public change[] change;
}
and
public class change {
public String id;
public String name;
}
and Json string like
[
{
"start_time": "8:00",
"end_time": "10:00",
"change": [
{
"id": "1",
"name": "Sam"
},
{
"id": "2",
"name": "John"
}
]
},
{
"start_time": "9:00",
"end_time": "15:00",
"change": [
{
"id": "1",
"name": "Sam"
},
{
"id": "2",
"name": "John"
}
]
}
]
Can somebody tell me what I did wrong ? Any idea why it won't work with array ?
As has been suggested, you need to use a list instead. Gson has pretty good documentation for using parametized types with the parser, you can read more about it here. Your code will end up looking like this:
Type listType = new TypeToken<List<Result>>() {}.getType();
List<Result> results = gson.fromJson(reader, listType);
for (Result r : results) {
System.out.println(r);
}