0

TLDR

I want a kotlin utility to call a 'GET' method on a restful API. Must I-the-programmer define a class that matches exactly the json output? Can I skip fields, so that the 'value/return object' class includes some of the returned fields, but not others?

Background

I'm new to kotlin and switch-hitting between python and kotlin.

I'm writing a utility to get data from a restful api. The vendor provided documentation and examples.

In python, the 'get' method would return a 'Map of maps'. The kotlin way, in contrast, is to return a 'well-defined' object.

I-the-coder can 'poke around' with this 'returned object' for the 'information I need'

Example

For example, let's say I want to 'get customer' from the rest api and my-utility only wants these fields:

  • 'name'
  • 'member since' date.

But let's say the 'get customer' json object includes a whole-bunch-of-info I-the-programmer don't care about:

  • "order history" (each entry in the 'order history' list is itself a complex object)
  • "customer preferences"

In kotlin: do i need to define a class that matches each and every field on the returned object? Can I define only the 'fields I care about' and have the 'json parser/object mapper' ignore all other fields?

Vs SOAP

Back in the day (e.g. 2006), applications providing SOAP services would generate java-client classes from the WSDL. Does the kotlin programmmer need to do the equivalent for restful programming?

Json Libraries

I didn't mention any specific parser (jackson, gson, klaxon) because I'm more interested in the general approach and assumed the "kotlin side" would be similar fo reach.

user331465
  • 2,984
  • 13
  • 47
  • 77
  • What are you talking about? Can you give any function reference? How do you retrieve your data? A library like e.g. [Fuel](https://github.com/kittinunf/Fuel/) returns a `JSONObject` or `JSONArray` if you want to. – creativecreatorormaybenot Mar 28 '18 at 15:51
  • You can do either, Kotlin places no limitations on your approach – Ken Wolf Mar 28 '18 at 16:09

1 Answers1

1

Most JSON parser libraries have an option to ignore unknown attributes in JSON data - for example, here's Jackson's documentation for this. If you set this option, you'll be able to create data classes that only contain fields you're interested in.

yole
  • 92,896
  • 20
  • 260
  • 197
  • +1. We are using kotlin and Spring MVC (with Jackson as serialization provider) with no problems. Just keep in mind some [pecularities](https://stackoverflow.com/questions/47982148/usage-of-jackson-jsonproperty-annotation-for-kotlin-data-classes) and you will be fine. – Oleg Mar 29 '18 at 21:40