Retrofit. Parse only nested object - android

I need to parse only one list of objects from JSON object with Retroft.
Here's my JSON file
I need only "similar" array from it. Also I've already created POJO for elements of this array
Is there a way to make this without making POJO for the rest of the JSON file?

Just make pojo with necessary fields:
data class ServerResponse(
val recipe: RecipeResponse
)
data class RecipeResponse(
val similar: List<RecipeBrief>
)

Related

Parsing API results on Android with Retrofit and Jackson or Gson

I am trying to parse the results of an API call which returns a unique first property.
{
"AlwaysDifferent12345": {
"fixedname1" : "ABC1",
"fixedname2" : "ABC2"
}
}
I am using retrofit2 and jackson/gson and cannot figure out how to cope with dynamic property names within the retrofit2 framework. The following works fine
data class AlwaysDifferentDTO(
#JsonProperty("AlwaysDifferent12345") val alwaysDifferentEntry: AlwaysDifferentEntry
)
I have tried
data class AlwaysDifferentDTO(
#JsonProperty
val response: Map<String, AlwaysDifferentEntry>
)
But this returns errors Can not instantiate value of type... The return value from the API is fixed i.e. map<string, object>.
I have read you can write a deserializer but it looks like I need to deserialize the whole object when all I want to do is just ignore the string associated with the response.
I have read
https://discuss.kotlinlang.org/t/set-dynamic-serializedname-annotation-for-gson-data-class/14758
and several other answers. Given unique properties names are quite common it would be nice to understand how people deal with this when using retrofit2
Thanks
Because the JSON doesn't have a 1-to-1 mapping Jackson can't map it automatically using annotations. You are going to need to make your own Deserializer.
In this tutorial you can learn how to create your own custom Deserializer for Jackson. https://www.baeldung.com/jackson-deserialization
In the tutorial you will see the first line under the deserialize function is
JsonNode node = jp.getCodec().readTree(jp);
using this line you can get the JSON node as a whole and once you have it you can call this function
JsonNode AlwaysDifferent12345Node = node.findParent("fixedname1");
Now that you have that node you can retrieve its value like shown in the rest of the tutorial. Once you have all the values you can return a new instance of the AlwaysDifferentDTO data class.

Kotlin and JSON Parsing

It's my first time dealing with JSON in android studio, and I'm trying to parse the response from google books API to JSON and then retrieve some info about the volume such as the title, author, and the description. the problem is there are JSON objects within the main JSON. Should I create a data class for each JSON?
the API link 'https://www.googleapis.com/books/v1/volumes?q=kotlin'
how i'm parsing it
val jsonResponse = gson.fromJson(body, JsonResponse::class.java)
the data classes that i created
data class JsonResponse
(val kind:String,val count:String,val items:List<JsonItems> )
data class JsonItems
(val kind:String,
val id:String,
val etag:String,
val self:String,
val volumeInfo:List<VolumeInfo>,
val saleInfo:List<SaleInfo>,
val accessInfo:ListList<AccessInfo> ,
val searchInfo:List<SearchInfo>)
is there any simpler solution to avoid unused data classes?
You need to have these classes to be able to parse the json, but then you can just create objects of other classes using those data (and drop the earlier instances).
Also, you don't need to include fields that you don't need.
You can parse without data classes and you can use other tools than Gson.
I had a use case similar to yours. I did not want to write data classes, but just get direct access to the specific data I was interested in from a larger nested JSON object.
I found a solution that worked well for me here
https://johncodeos.com/how-to-parse-json-in-android-using-kotlin/
using JSONTokener https://developer.android.com/reference/org/json/JSONTokener
Based on these examples, some code for parsing books might look like:
// response is a String with the JSON body
val jsonObject = JSONTokener(response).nextValue() as JSONObject
val items = jsonObject.getString("items") as JSONArray
for (i in 0 until items.length()) {
val volumeInfo = items.getJSONObject(i).getString("volumeInfo")
val title = volumeInfo.getString("title")
}
Another Stackoverflow post with other suggestions is here How to parse JSON in Kotlin?

Post request body is not correct thus 400 error - Kotlin

I am facing a problem when trying to send an Http post request to the backend of my application. I am trying to send a post request like this :
{"a":[{"data":"https://news.google.com/rss/search?q=Pallini&hl=el"}]}
and instead it is being send something like this:
{"a":[{"data\":\"https://news.google.com/rss/search?q=Pallini&hl=el"}]}
or:
{"a":[{\"data\":\"https://news.google.com/rss/search?q=Pallini&hl=el\"}]}
So, I have a list that contains strings and every time I add the string that I want it to be shown in the json array, the code is like this:
var arrayListForA: ArrayList<JsonElement>? = arrayListOf()
config.forEach {
arrayListForA?.add(it)
}
The config is an another list that contains the jsons object as strings.
My question is, if there is any way to create the http post request body in Kotlin with the use of classes, objects etc, in a more automated way ?! for example, instead of a list with strings, I could use a list with Data class objects.
val dataList : ArrayList<Data> = arrayListOf()
where Data class is :
#Parcelize
data class Data(
#Expose #SerializedName("data") val data: String?
) : Parcelable
Is there any solution/idea to send the body of the post request as I need it ?
You can use retrofit and okhttp for this in Android. Retrofit helps you deal with networking easily. Also you will be able to post a custom data model as body in the api request. The interface will look something like given below. You can read more about retrofit here. retrofit
#POST(Urls.PURCHASE)
fun purchase(#Body purchaseAddonReqModel: PurchaseReqModel):Single<BaseResponse<EmptyResponse>>
Here you can add your custom model by adding the #Body annotation

Create a ArrayList of data class objects from a String in Kotlin

I have a Kotlin data class
data class Item (val content: String) {}
In my app I use an myData: ArrayList<Item>.
To provide persistant storage the app writes this list to a file everytime it is changed:
configFile.writeText(myData.toString())
At startup it reads the file and with configfile.readFile(). The returned string look like this:
[Item(content=Click #1), Item(content=Click #2)]
How can I create the arraylist from this string?
You can write data in some well known format such as JSON or XML. You can still parse your written string, but JSON / XML can be preferrable.
For reading / writing JSON / XML, you can use jackson library which is quite easy to use.
Here is the link for quickstart.

Parsing Json dynamically.

I am working on json currently in android, but now i follow getter and setter methods to parse json. For example. if there are 5 fields in json string, so create 5 getter and setter methods in one class and accordingly parse the string.
But now in future if one more field increases in json string, then again i need to add one more getter and setter method in that class.
So my question is can we parse json without getter setter, without any class? so that if json changes in future it can be handled well without adding new getter and setter method.
Please let me know the dynamic way to handle json.
you can use these web site http://www.jsonschema2pojo.org/
for creating a class if in future any field increase just put the json in that it will automatically create a class for you .

Categories

Resources