I am creating one application,in my application I am using json parsing,I am sending request to server for
after click on button request will be send,and i will get response
{"searchresult":
[ {"match_detail_id":369,"profile_id":"GM686317","name":"Sonal Patel","image":"","location":"Rajkot ,Gujarat ,India","mothertongue":"Gujarati","religion":"Hindu","occupation":"Professor \/ Lecturer","education":"Masters - Arts\/ Science\/ Commerce\/ Others"}
, {"match_detail_id":396,"profile_id":"GM780609","name":"Hetal Trivedi","image":"","location":"Rajkot ,Gujarat ,India","mothertongue":"Gujarati","religion":"Hindu","occupation":"Administrative Professional","education":"Bachelors - Arts\/ Science\/ Commerce\/ Others"}
, {"match_detail_id":1078,"profile_id":"GM540027","name":"Shruti Dave","image":"","location":"Rajkot ,Gujarat ,India","mothertongue":"Gujarati","religion":"Hindu","occupation":"Education Professional","education":"Masters - Arts\/ Science\/ Commerce\/ Others"}
]
}
I want to show this response in another activity
Parse the response you have received, and store it in a arrayList with the custom object you create to store your each response line.
{"match_detail_id":369,"profile_id":"GM686317","name":"Sonal Patel","image":"","location":"Rajkot ,Gujarat ,India","mothertongue":"Gujarati","religion":"Hindu","occupation":"Professor \/ Lecturer","education":"Masters - Arts\/ Science\/ Commerce\/ Others"}
this is your one line, so object class would be like this -
public class ResultObejct implements parcelable {
String match_detail_id;
String profile_id;
String name;
String image;
public String getName(){ //set getter and setters
return this.name;
...
...
...
}
And Like this link, put your data in intent,
Intent i = new Intent(...);
i.putExtra("data", new DataWrapper(yourArrayList));
and retrieving in next activity:
DataWrapper dw = (DataWrapper) getIntent().getSerializableExtra("data");
ArrayList<Parliament> list = dw.getParliaments();
Store the response data in a map and pass it to next activity.
Related
Why is price null here?
JSON is retrieved from here (you could also use multiple parameters, that is why the below object uses Maps; example). Here is CoinGeckoCoinPrice:
public class CoinGeckoCoinPrice {
#Expose
private Map<String, Map<String, Double>> price;
public double getPrice(String slug, String pair) {
...
}
}
Here is my Retrofit2 call:
#GET("/api/v3/simple/price")
Call<CoinGeckoCoinPrice> getCoinPrice(#Query("ids") String coinSlugs, #Query("vs_currencies") String pairs);
I checked logcat for any GSON error message and there is none. So why would price be null?
It works if I change Retrofit2 call to use JsonObject:
#GET("/api/v3/simple/price")
Call<JsonObject> getCoinPrice(#Query("ids") String coinSlugs, #Query("vs_currencies") String pairs);
But I want to wrap the object so I can write data retrieval functions in the CoinGeckoCoinPrice class.
The Json you are getting back doesn't have a price property on it, so Gson doesn't know that it should be parsing the bitcoin object and its price in USD to that object. Given that your returned data can be for any key (i.e. bitcoin, ethereum...) and its properties can also have any keys (i.e. usd, euros...) you'll need to manually parse this by giving Gson a custom adapter to work with.
I'm using Retrofit 2 and I need to send request body. The problem is somehow the value is converted to string. On the example below, you can see that items and totalPrice which should be array and number respectively are converted to string.
{ cashierId: 'fff7079c-3fc2-453e-99eb-287521feee63',
items: '[{"amount":3,"id":"602a79e3-b4c1-4161-a082-92202f92d1d6","name":"Play Station Portable","price":1500000.0}]',
paymentMethod: 'Debt',
totalPrice: '4500000.0' }
The desired request body is
{ cashierId: 'fff7079c-3fc2-453e-99eb-287521feee63',
items: [{"amount":3,"id":"602a79e3-b4c1-4161-a082-92202f92d1d6","name":"Play Station Portable","price":1500000.0}],
paymentMethod: 'Debt',
totalPrice: 4500000.0 }
Here's the service
#POST("api/sales")
#FormUrlEncoded
Call<Sale> createSale(
#FieldMap Map<String, Object> fields
);
And this is how I call createSale
Map<String, Object> fields = new HashMap<>();
fields.put("cashierId", UUID.fromString("fff7079c-3fc2-453e-99eb-287521feeaaa"));
fields.put("totalPrice", totalPrice);
fields.put("paymentMethod", paymentMethod);
fields.put("items", jsonArray);
Call<Sale> call = retailService.createSale(fields);
Is it possible to send those values as number and array, not as string?
The conversion most certainly happens because you are using #FormUrlEncoded.
According to the documentation:
Field names and values will be UTF-8 encoded before being URI-encoded in accordance to RFC-3986.
A solution would be to use a model class instead of a Map. I see you already have a Sale class. If it looks like something like this:
public class Sale {
String cashierId;
int totalPrice;
String paymentMethod;
ArrayList<SomeObject> items;
}
you can simply do like this:
// in service
#POST("api/sales")
Call<Sale> createSale(#Body Sale sale);
// when doing the call
Sale sale = new Sale();
// set everything in your object
// then
Call<Sale> call = retailService.createSale(sale);
I am using the Retrofit (2.3.0) and I use the Retrofit-GSON-converter to create a POJO.
Let's say I have the following class:
public class Flight {
#SerializedName("fromCity")
private String fromCity;
#SerializedName("toCity")
private String toCity;
#SerializedName("fromAirportName")
private String fromAirportName;
#SerializedName("toAirportName")
private String toAirportName;
// Getters + Setters
}
Now when I use a retrofit call to fetch the model, it parses without error and I get a List with all values set but sometimes I get an empty string for fromCity and toCity from my server.
What I want is to set the value of fromCity and toCity to custom values once the object is constructed such that I do not iterate over the List of the objects and update them individually.
Its the data for a quiz, which include "id" as question ID and "test_id" as a quiz ID. I need to fetch all the question(no. of question may differ) and options with correct answer and need to populate it in a recyclerview.
[
{
"id":"13",
"test_id":"1",
"question":"find out relationship with the third word.",
"options":"[\"speed\",\"hiking\",\"needle\",\"direction\"]",
"correct_answer":"3",
"create_date":"2016-10-27 07:37:39",
"update_date":null
},
{
"id":"14",
"test_id":"1",
"question":"find out which of the answer choices completes the same relationship with the third word.",
"options":"[\"not\",\"set\",\"get\",\"pet\"]",
"correct_answer":"3",
"create_date":"2016-10-28 07:37:39",
"update_date":null
},
{
"id":"15",
"test_id":"1",
"question":"the same relationship with the third word.",
"options":"[\"jet\",\"read\",\"nor\",\"sour\"]",
"correct_answer":"3",
"create_date":"2016-10-28 10:37:39",
"update_date":null
},
{
"id":"16",
"test_id":"1",
"question":"A good way to figure out the relationship ",
"options":"[\"trekking\",\"hiking\",\"seed\",\"turn\"]",
"correct_answer":"3",
"create_date":"2016-10-28 18:37:39",
"update_date":null
}
]
I have used this code:
String res = new QuestionRequest(getActivity().getApplicationContext(), "level_question").execute(test_id).get();
JSONArray result = new JSONArray(res);
List<DataQuestion> data=new ArrayList<>();
for(int i=0;i<result.length();i++){
JSONObject json_data = result.getJSONObject(i);
DataQuestion rowdata = new DataQuestion();
rowdata.id= json_data.getString("id");
rowdata.test_id= json_data.getString("test_id");
rowdata.question= json_data.getString("question");
rowdata.answer_choices= json_data.getString("answer_choices");
rowdata.correct_answer= json_data.getString("correct_answer");
data.add(rowdata);
}
I have stored it in arraylist. Now how should send it another fragment. I tried to send data using Bundle but don't know how to send arraylist.
where:
DataQuestion.java is
public class DataQuestion {
public String id;
public String test_id;
public String question;
public String answer_choices;
public String correct_answer;
}
I suggest you to use the library Retrofit (https://square.github.io/retrofit/) to call API request and serialize the response. In your case you will create a class with many field (id, test_id, question, options,...).
And then you create an adapter for your recyclerview which accept your model class. And finally you display your item with cardview for example.
Its better if you post what you have tried to parse this json. Parsing json is very easy in android you just have to create this a JSONArray or JSONObject from the data you have. In your case its a JSONArray.
Later you can create your models which will contain the json data , you can pass the model to a adapter and user that adapter in a recyclerview or list.
You can use Volley to fetch the data and create a JSONObject to parse the Response into a list of Questions (using model) and then pass that list to an adapter where you can set the question in your list item in RecyclerView/ListView.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
can any one help me to parse this json using gson library.
I could not create the correct POJO class for this Json
{"status":"ok","result":[{"name":"Al Mansoori Villa in Al Khawaneej","reference":"UB5647","link":"\/index.php?r=apiv1\/projects\/view&id=21570"},{"name":"Mr. Mohammad Dhanhani Villa in Dibba","reference":"UB6046","link":"\/index.php?r=apiv1\/projects\/view&id=22970"},{"name":"Villa in Al Barsha","reference":"UB6664","link":"\/index.php?r=apiv1\/projects\/view&id=25877"},{"name":"Bin Omeir Hospital in Abu Dhabi","reference":"UB6054","link":"\/index.php?r=apiv1\/projects\/view&id=23291"}]}
Thanks in advance
check this link for Parsing JSON Array using GSON
This might help you...
I was able to parse this using POJO. You have to make sure that under Annotation style you select GSON and under Source type: you select JSON. Then in your code convert to
Single Object
/**
* This will convert json string to User object.
* #param jsonUserString
* #return <b>User object/b>
*/
public User convertFromJsonStringToUserObject(String jsonUserString){
Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Type listType = new TypeToken<User>() {}.getType();
return g.fromJson(jsonUserString, listType);
}//END
ArrayList of objects.
/**
* Convert string to {#link ArrayList} of {#link Address}
* #param jsonAddress <b>String</b> json string
* #return <b>{#link ArrayList} of {#link Address}</b>
*/
public ArrayList<Address> convertJsonStringToAddressObjectArray(String jsonAddress){
ArrayList<Address> addressList = new ArrayList<Address>();
Type listType = new TypeToken<List<Address>>() {}.getType();
Gson g = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
addressList=g.fromJson(jsonAddress, listType);
return addressList;
}//END
You will need to have a class as per your response:
In your case something like shown below:
public class MyResponse{
public String status = "";
public List<Result> result;
public MyResponse{
result = new ArrayList<MyResponse.Result>();
}
//getter setter for status and result
public class Result{
public String name="";
public String reference="";
public String link="";
public Result(){
}
//getter setter for name, reference, link
}
}
And then just parse it as:
MyResponse response = new Gson().fromJson(responseString,
MyResponse.class);
Hope this helps.
Response seems a straightforward one with the String of status and an arrayList of "Result"(s)
To do it directly using Gson, you can set your model class in the same way with an independent class for Result array objects.
Should work with:
class JsonResponseModel{
String status;
#SerializedName("result") //optional to use, you can name the variable as "result"
ArrayList<ResultInResponse> resultArrayList;
//getters setters
//toString for the class, works well to verify data populated
}
Now the result class
class ResultInResponse{
String name;
String reference;
String link;
//getters setters
//toString for the class
}
Implementation:
Gson gson = new Gson();
jsonResponseModel = gson.fromJson(yourStringContent,
JsonResponseModel.class);
Easy to map it that way.