Gson toJson and ArrayList in Kotlin - android

Similarly to this question, I would like to convert an object (actually, it is a API response from retrofit) to a json string, so it would be simpler to store it somewhere.
The response structure is something like these:
{
"metadata": {
"count": 0,
"type": "string"
},
"results": [
{
"obj1": {
"param1": "s1",
"param2": "s2"
},
"obj2": {
"param3": 0,
"param4": 0,
"param5": 0
},
"obj3": 0,
"obj4": "27/12/2017"
}
]
}
Using retrofit2, I have the results array stored in a List<MyResponse.Result> and that's the parameter I'm passing to Gson().toJson, like so:
var contentResponse: String = ""
try{
this.contentResponse.plus(Gson().toJson(response))
} catch (e: Exception){
Log.e("Gson error", e.toString())
}
Unfortunately, I'm getting no exception but my contentResponse keeps empty. I`ve tried to use the method in the question mentioned above, but got the same outcome. Any advises?
PS: If there is an easier way to get the retrofit response in a String, it could help as well.

Strings are immutable in JVM. Calling
this.contentResponse.plus(Gson().toJson(response))
is equivalent to
this.contentResponse + (Gson().toJson(response))
This way you can see better that you are not assiging the result to anything. Change it to
this.contentResponse = this.contentResponse.plus(Gson().toJson(response))

Related

How to retrieve the list of all GitHub repositories of a person? parsing json list with no key value

I know this question has been answered at this post with same question. however, my question is the Json response by the most upvoted answer will be a json list with no key value.
(you can also check the sample json from the official github website)
I am using Moshi library to parse json. However, I have no idea how to parse that Json list whose key value is not set.(only a list present in the Json with no Key value for that list)
this is what it looks like though
[
{
"id": 1296269,
"node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5",
"...": "...",
...
},
{
"id": 1296255,
"node_id": "somevalue",
"...": "...",
}
...
]
since the purpose of asking this question is to get a list of repositories of a user, you could leave any code snippet to get that type of list Json to Kotlin data class.
I appreciate your help in advance.
Try this one for Array list
inline fun <reified T> Any?.getResponseInArrayList(): ArrayList<T?>? {
return try {
val token: TypeToken<ArrayList<T>> = object : TypeToken<ArrayList<T>>() {}
val json = Gson().toJson(this)
Gson().fromJson(json, token.type)
} catch (e: Exception) {
Log.e("GSON ERROR ", "" + e.message)
null
}
}
use like this
val model = yourJsonString.getResponseInArrayList<YouJsonModel>()

Consuming polymorphic json "data: { put_anything_here }" with Gson & Retrofit

I'm not sure if polymorphic is the right term to use so my apologies.
I'm working with the following API:
Request body:
{
"user_id": "user_id",
"command": "submit_document",
}
Response:
{
"result": "success",
"code": 200,
"status": "ok",
"screen": "documents_rejected", // This is unique for different `data`
"next_screen": "",
"message": "Successful",
"data": {
// `data` is always a json object with known fields and parameters
}
}
I have data classes ready for different types of data responses like:
data class PhoneData(
#SerializedName("phone_number")
val phoneNumber: String? = null,
#SerializedName("phone_status")
val phoneStatus: String? = null
)
for "screen": "phone" and the following for another screen:
data class Data(
val deepLink: String? = null
)
The problem is, at the start, I have to make the following request to retrieve the current screen:
{
"user_id": "user_id",
"command": "get_current_screen",
}
which returns a similar response as above:
{
"result": "success",
"code": 200,
"status": "ok",
"screen": "main_screen", // Different types of screen types are known.
"next_screen": "",
"message": "Successful",
"data": {
// `data` is always a json object but the object could contain anything depending on the `screen` type.
}
}
but the data field could contain anything depending on the screen
data class SplashScreenData(
// How do I make this data class combine all other data classes? One ugly approach is to add all the fields from different `data` classes here and use this one only.
)
I found about the RuntimeTypeAdapterFactory for polymorphic cases but am not sure how to make it work when there's no "type" like field within the data object (screen is unique but it's outside the data object).
It would be very helpful if someone has a solution or could point me in a direction.
val frameTextReceived: String = frame.readText()
val jsonObject = JsonParser.parseString(frameTextReceived).asJsonObject
val type = when (jsonObject.get("type").asString) {
TYPE_JOIN_ROOM -> JoinRoom::class.java
TYPE_GAME_MOVE -> GameMove::class.java
TYPE_DISCONNECT_REQUEST -> DisconnectRequest::class.java
else -> BaseModel::class.java
}
val payload = gson.fromJson(frameTextReceived, type)
This is my solution, here I have type parameter by which I can know in which class I have to deserialize the object but in your case you have screen parameter, you can use this.

How to GET data from single value inside JSON Object from JSON Array?

I am new to Kotlin beginner and trying to create a code to fetch data from JSON.
I'd like to fetch the data from "value" inside "forecastMaxtemp".
Here is my code. I am tried as below but not successful.
...
Response.Listener { response ->
temp.text =
response.getJSONArray (name"weatherForecast").
getJSONObject(0).
getJSONObject("forecastMaxtemp").
getString(name"value")
},
JSON Data
{"generalSituation":No Alarm",
"weatherForecast":[{
"forecastDate":"20211004",
"week":"Monday",
"forecastWind":"East force 4 to 5.",
"forecastWeather":"Sunny periods.",
"forecastMaxtemp":{"value":31,"unit":"C"},
"forecastMintemp":{"value":27,"unit":"C"},
...
...
]
}
Your JSON has an issue, I think this is the right format:
{
"generalSituation": "No Alarm",
"weatherForecast": [
{
"forecastDate": "20211004",
"week": "Monday",
"forecastWind": "East force 4 to 5.",
"forecastWeather": "Sunny periods.",
"forecastMaxtemp": {
"value": 31,
"unit": "C"
},
"forecastMintemp": {
"value": 27,
"unit": "C"
}
}
]
}
to get the value from "forecastMaxtemp",
val json = JSONObject("YOUR_JSON")
val obj = json.getJSONArray("weatherForecast").get(0) as JSONObject
val value = obj.getJSONObject("forecastMaxtemp").getInt("value")
{"value":31,"unit":"C"} here 31 is int, so use getInt() function.
response.getJSONArray ("weatherForecast").
getJSONObject(0).
getJSONObject("forecastMaxtemp").
getInt("value")
}

Unable parse the json data in android even by following the actual procedure

iam trying to parse the json data which is shown below.i got output for other Json response by following this procedure but for this i cant get data.
{
"totalResults": 7,
"startIndex": 1,
"hasMoreResults": false,
"itemsPerPage": 10,
"results": [
{
"offering_temp_id": {
"displayName": "Cool Course",
"id": "cours000000000004841",
"course_no": "00006081",
"version": null
},
"delivery_id": {
"displayName": "Instructor-Led",
"id": "eqcat000000000000004"
},
"student_id": {
"id": "emplo000000006156648",
"displayName": "Venkat Rao",
"person_no": "VRAO"
},
"reg_no": "00008341",
"wlist_on": "2017-08-17T08:59:39.843-0400",
"wlist_priority": 5,
"Max_Count": null,
"Current_Count": null,
"is_no_show": false,
"is_walk_in": false,
"offering_action_id": {
"id": "ofapr000000000013441",
"displayName": "00009081"
},
"class_id": {
"id": "class000000000006981",
"displayName": "Cool Course"
},
"elements_to_complete": 0,
"status": "100",
"id": "regdw000000000012581"
},
// total 7 fields
],
"facets": []
}
And iam using the parser procedure as follows
public class EnrollmentParser {
public ArrayList<EnrollmentData> getData(String respnose)//EnrollmentData is my pojo class contains 4 strings and its getters and setters
{
ArrayList<EnrollmentData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(respnose);
JSONArray array = mainObj.getJSONArray("results");
for(int i = 0;i<array.length();i++)
{
EnrollmentData data = new EnrollmentData();
JSONObject resObj = array.getJSONObject(i);
data.setReg_num(resObj.getString("reg_no"));
data.setElements_to_complete(resObj.getString("elements_to_complete"));
data.setW_list_on(resObj.getString("wlist_on"));
data.setW_list_priority(resObj.getString("wlist_priority"));
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
}
when iam trying to display the dataList returned from above method i didnt get any data i got response like
Suggest me any changes that are required to get the response
There is no faulty parsing code, everything is fine (although better use optString).
By default , the toString function will return the type '#' reference value so
You need to override toString in EnrollmentData class to see the actual content inside EnrollmentData object
You can also collect your list objects as single string using
String str = Arrays.toString(yourList.toArray());
How to print out all the elements of a List in Java?
Why don't you use Gson to convert json into object easily instead of getting the field and set them one by one?
You may check out
https://github.com/google/gson

Is this a valid JSON?

I am successfully parsing a json which looks like this, which in this particular case represents an array with 2 items:
{
"items": [
{
"id": 1,
"name": "John"
},
{
"id": 2,
"name": "Mark"
}
]
}
However, I can't figure out how to parse one like this:
{
"items": {
"1": {
"id": 1,
"name": "John"
},
"2": {
"id": 2,
"name": "Mark"
}
}
}
As you can see, the second json is pretty similar to previous one, except after items it begins with "{", which means it is an object not an array, but I need that data to treat like an array.
Is this an invalid json, or I am missing something?
EDIT:
Ok, got it. The json is valid.
Let me please reformulate the question.
What I am actually looking for is how could I get the second json into a list of items.
Somewhere in the code I am doing this:
ItemsResponse itemsResponse = JsonMarshaller.fromJson(ItemsResponse.class, response);
and the ItemsResponse class:
public class ItemsResponse {
private List<Item> items;
// getters and setters
}
but it fails with an exception which says that the beginning of the json is an object, not an array.
SOLUTION:
The correct way is to use a Map instead of the List:
public class ItemsResponse {
private Map<String, Item> items;
// getters and setters
}
Read the answer of Ahmad Dwaik 'Warlock' here
You can check your json here

Categories

Resources