Send a key value list object to retrofit - android

I want to send this
"question_id": 1,
"answer_id": {
"answerId1": "value1",
"answerId2": "value2"
}
through retrofit in android
I sent this
"question_id": 1,
"answer_id": [
1,
2
]
like that
#FormUrlEncoded
#POST(".....")
#Field("question_id") String questionId, #Field("answer_id[]") ArrayList<String> answerId)
how to do the same for the first request? btw HashMap<String,String> is not working

Try this
public interface myService {
#POST("/api/mypath/test")
#FormUrlEncoded
void getPositionByZip(#Query("question_id") String question_id, #FieldMap Map<String, String> answer_id);
}
// Map params need set key and value pair like
// answer_id.put("answerId1","value1");
// answer_id.put("answerId2","value2");

You can use Gson Class and it converts to a string :
List<Answer> answerlist= new ArrayList<>();
Answer model = new Answer();
answerlist.add(model);
Gson gson = new Gson();
String finallocation = gson.toJson(answerlist);
#FormUrlEncoded
#POST("example.com/question")
Observable<Response> sendAnswer(
#Field("question_id") String question_id,
#Field("answer") String answer);

Related

How to create JSONObject from ArrayList<Object> to make post request?

I am trying to post data into server using JSONObject as request. And I dont know how to create JSONObject from ArrayList with following type of data.
{"AnswersList":[
{
"questionID": 1,
"question": "What is yout name?",
"questionType": "STRI",
"questionOrder": 1,
"answer":"Avishek",
"choiceList": []
},
{
"questionID": 2,
"question": "Sports?",
"questionType": "MULT",
"questionOrder": 2,
"answer":"1,2",
"choiceList": [
{
"choiceID": 1,
"choiceName": "Football",
"choiceOrder": 1
},
{
"choiceID": 2,
"choiceName": "Basketball",
"choiceOrder": 2
}
]
}]}
Can anyone please help me to solve this problem.
I have create two model classes for handling the JSON. First one is Question.java for second is Choice.java
Model classes are:
Question.java
public class Question {
#SerializedName("questionID")
public String questionID;
#SerializedName("question")
public String question;
#SerializedName("questionType")
public String questionType;
#SerializedName("questionOrder")
public String questionOrder;
#SerializedName("answer")
public String answer;
#SerializedName("choiceList")
public ArrayList<Choice> choices = new ArrayList<>();
#SerializedName("isRequired")
public boolean isRequired;
//getter and setter methods
}
Choice.java
public class Choice {
#SerializedName("choiceID")
private String choiceID;
#SerializedName("choiceName")
private String choiceName;
#SerializedName("choiceOrder")
private String choiceOrder;
//getter and setter method
}
I've tried this code but did not work
DatabaseHelper databaseHelper = new DatabaseHelper(mContext);
ArrayList<Question> questionsAnswer = new ArrayList<>();
questionsAnswer.addAll(databaseHelper.getQuestionList());
Log.v(TAG, "size of question answer list : " + questionsAnswer.size());
Map<String, Object> jsonParams = new ArrayMap<>();
//put something inside the map, could be null
JSONArray jsArray = new JSONArray(questionsAnswer);
jsonParams.put("AnswersList", jsArray);
First of all, I'll suggest to use Retrofit library for requests (https://square.github.io/retrofit/)
For creating a json String from your object you can use Gson library
Gson gson = new Gson();
String jsonInString = gson.toJson(obj);
Update
don't forget to add Gson dependency on your gradle file
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
Parsing JSON Objects & Arrays on Java we should use GSON Library
Add gradle File:
implementation 'com.google.code.gson:gson:2.8.2'

Android: Fetch the very first value in JSON data using Retrofit Library

I am using the Retrofit Library in Android to read the JSON data.
I want to only read the country names from the below JSON i.e just the value. Is it possible to read such JSON data using Retrofit Library?
{
"China": ["Guangzhou", "Fuzhou", "Beijing"],
"Japan": ["Tokyo", "Hiroshima", "Saitama", "Nihon'odori"],
"Thailand": ["Bangkok", "Chumphon", "Kathu", "Phang Khon"],
"United States": ["Mukilteo", "Fairfield", "Chicago", "Hernando", "Irving", "Baltimore", "Kingston"],
"India": ["Bhandup", "Mumbai", "Visakhapatnam"],
"Malaysia": ["Pantai", "Kuala Lumpur", "Petaling Jaya", "Shah Alam"]
}
List<String> list = new ArrayList<>();
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
list.add(key);
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}
Log.d("TAG",list.toString());
You can use HashMap<String,ArrayList<String>> as retrofit result obj and get the keys.
or just get it with string then cast it to hasmap
val typeToken: Type = object : TypeToken<HashMap<String, ArrayList<String>>>()
{}.type
val result = Gson().fromJson<HashMap<String, ArrayList<String>>>(tmp, typeToken)
then you can iterate trough the keys.
for example :
public class Country{
private List<String> name;
}
An associative array translates to a Map in Java:
Map<String, Country > countries = new Gson().fromJson(json, new TypeToken<Map<String, Country >>(){}.getType());
in retrofit just add to model class:
#Expose
private Map<String, Country> result;

Retrofit 2 - Post FieldMap with Body Object

I want to post a HashMap and a Object using Retrofit.
I tried this code below but received IllegalArgumentException.
#POST("update")
Call<RSP010> postApi010(#FieldMap HashMap<String, String> defaultData, #Body User user);
Logcat
java.lang.IllegalArgumentException: #FieldMap parameters can only be used with form encoding. (parameter #1)
But when I add #FormUrlEncoded. It said
java.lang.IllegalArgumentException: #Body parameters cannot be used with form or multi-part encoding. (parameter #2)
UPDATE CODE
public static HashMap<String, String> defaultData(){
HashMap<String, String> map = new HashMap<>();
map.put("last_get_time", String.valueOf(SharedPreferencesHelper.getLongValue(AppConstants.LAST_GET_UPDATE)));
map.put("duid", SharedPreferencesHelper.getStringValue(AppConstants.DUID));
return map;
My Object which I want to post
int profile_id;
private String name;
private String name_kana; // あいうえお
private int gender; // 1 nam 2 nu
private String birth_day;
private String birth_time;
private String birth_place;
private String relationship;
Explain:
I want to post multiple variables via API to server. FieldMap defaultData for default variables I want to use in every API.
https://futurestud.io/tutorials/retrofit-send-objects-in-request-body I've read this, it said instead of posting all separate variables of an object, I can post an object directly.
You can send #Body User user with #FieldMap HashMap<String, String> defaultData like
String user = new Gson().toJson(user);
HashMap<String, String> map = new HashMap<>();
map.put("last_get_time", String.valueOf(SharedPreferencesHelper.getLongValue(AppConstants.LAST_GET_UPDATE)));
map.put("duid", SharedPreferencesHelper.getStringValue(AppConstants.DUID));
map.put("duid", SharedPreferencesHelper.getStringValue(AppConstants.DUID));
map.put("user", user);
OR
Use #PartMap Map<String, RequestBody>
#Multipart
#POST("update")
Call<RSP010> postApi010(#PartMap Map<String, RequestBody> defaultData);
And create your request parameters
Map<String, RequestBody> map = new HashMap<>();
map.put("last_get_time", toRequestBody(String.valueOf(SharedPreferencesHelper.getLongValue(AppConstants.LAST_GET_UPDATE))));
map.put("duid", toRequestBody(SharedPreferencesHelper.getStringValue(AppConstants.DUID)));
RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),new Gson().toJson(user));
map.put("user", body);
// This method converts String to RequestBody
public static RequestBody toRequestBody (String value) {
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
return body ;
}
Modify your method to:
#POST("update")
Call<RSP010> postApi010(#Query("last_get_time") String lastGetTime,
#Query("duid") String uid,
#Body User user);

Gson array parser

I have json response in this form:
String json = "{\"0\":{ \"title\" :\"title 1\" , \"time\" : \"15:00\" } ,\"1\":{ \"title\" : \"title 2\" , \"time\" :\"16:00\" }}";
And here is my class, I am trying to map it to:
public class News implements Seriaizable{
#SerializedName("title")
private String title;
#SerializedName("time")
private String time;
}
I am struggling because i have an array without a name which contains loads of other arrays.
Gson gson = new GsonBuilder().setPrettyPrinting().create();
News obj = gson.fromJson(reader, News.class);
Would anyone be able to guide me into right direction?
Your JSON is incorrect in format. I have added some commas to correct it.
You can solve this problem by using maps :
String json = "{\"0\":{ \"title\" :\"title 1\" , \"time\" : \"15:00\" } ,\"1\":{ \"title\" : \"title 2\" , \"time\" :\"16:00\" }}";
Gson gson = new Gson();
Type type = new TypeToken<Map<Integer, News>>() {}.getType();
Map<Integer, News> map = gson.fromJson(json, type);
Ref : https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples

Parse Irregular JSON format in android

Hello friends i have following JSON foramt
{
"Communities": [],
"RateLog": { "83": 5,"84": 4, "85": 5,"92": 5,"93": 4,"94": 5,"95": 5,"97": 5,"99": 4,"100": 5,"102": 5,"103": 5,"104": 5,"105": 5,"106": 5,"108": 4,"109": 4,"110": 4,"111": 5,"112": 4,"113": 4,"114": 4,"115": 5,"116": 5,"117": 5,"118": 4,"119": 5, "120": 5,"121": 4,"122": 5,"123": 4,"124": 4,"125": 4,"126": 5, "142": 5,"1150": 4, "1151": 4,"1152": 4, "1153": 4,"1154": 4, "1155": 4,"1156": 4, "1158": 5}
}
so how can i parse it any idea?
You can turn it into legal JSON by enclosing it in braces. So if you have the string:
var badJSON = '"RateLog" : { "1156": 4, ... }';
You can do this:
var goodJSON = '{' + badJSON + '}';
var parsed = JSON.parse(goodJSON);
EDIT: The above answer was before your edit. With the new format, the string is valid JSON, so simply call JSON.parse() and pass the string to get the corresponding object structure.
You must improve your json format like this :
"RateLog":[
{
id1:1156
id2:4
{
id1:1155
id2:4
}
{
id1:1155
id2:4
}
..]
JSONObject json = new JSONObject(jsonString);
JSONArray array = json.getJSONArray("Communities");
for (int i = 0; i < array.length(); i++) {
// do stuff
}
JSONObject rateJson = json.getJSONObject("RateLog");
rateJson.getInt("83"); //Will return 5
.
.
.
for more got through this tutorial
http://www.mkyong.com/java/json-simple-example-read-and-write-json/
You can use Google's Gson library to parse your response.
Using POJO class
String jsonString = "Your JSON string";
Pojo pojo = new Gson().fromJson(jsonString, Pojo.class);
class Pojo {
ArrayList<String> Communities;
HashMap<String, Integer> RateLog;
//Setters and Getters
}
Without using POGO class
Gson gson = new Gson();
String jsonString = "Your JSON string";
JsonObject jsonObj = gson.fromJson(jsonString, JsonElement.class).getAsJsonObject();
HashMap<String, Integer> RateLog = gson.fromJson(jsonObj.get("RateLog").toString(), new TypeToken<HashMap<String, Integer>>(){}.getType());
You can iterate through RateLog HashMap to get key, value pairs.

Categories

Resources