Android string to json kotlin

Kotlin – Convert object to/from JSON string using Gson

In this tutorial, we’re gonna look at way to parse JSON into Data Class, Array, Map and do the opposite: convert object, Array, Map to JSON in Kotlin with the help of Gson library.

Add Gson to your Kotlin project

Gson is a Java/Kotlin library for converting Java/Kotlin Objects into JSON representation, also a JSON string to an equivalent Java/Kotlin object.

We have some ways to add Gson library to our Kotlin project.

Go to Maven Repository and download .jar file.

Create a Kotlin Data Class

We will need a plain Class first. Let’s call it Tutorial .

Gson.fromJson() method

com.google.gson.Gson package provides helpful method for deserializing JSON called fromJson() .

  • T : type of the desired object
  • json : could be a JsonElement object, a Reader object or a String
  • classOfT : class of T
  • typeOfT : specific genericized type

Gson.toJson() method

com.google.gson.Gson also provides toJson() method for JSON serialization.

  • src : type of the desired object
  • typeOfSrc : could be a Data Class type, List type, Array type, Map type…

Kotlin parse JSON to Data Class Object

The example shows you how to:

  • convert JSON to Data Class from a String object
  • parse JSON to Data Class from a JSON file with FileReader

The result in console looks like this-

Kotlin parse JSON to Array or List

Because the object we want to parse JSON to is an array-like object. So we must use fromJson​(json, typeOfT) .

By default, Kotlin/Java doesn’t provide a way to represent generic types.
To get Type of an Array , we use TypeToken .

For example, to create a type literal for Array , we create an empty anonymous inner class like this:

Let’s do the parsing right now.

Now check the result:

The way we use Gson to parse JSON to List , MutableList or ArrayList are the same.

We only need to change the input type:

The major difference among these Type is that:
– Array has a fixed size, but it is mutable.
– List can adjust its size dynamically, but unmutable.
– MutableList is mutable and we can adjust its size dynamically.
– ArrayList is a class that implements MutableList .

Kotlin parse JSON to Map

For Kotlin Map , we also need to use fromJson​(json, typeOfT) with the help of TypeToken .

Читайте также:  Remote mouse pro для андроид

Let’s parse JSON to a Kotlin Map now.

And the result after running the code will be:

We can also apply these methods to parse JSON file from assets in an Android Application.

Convert Object to JSON string in Kotlin

The examples will show you how to convert Data Class/List/Array/Map object to JSON string.

If you want to get pretty JSON, you can use an additional package called com.google.gson.GsonBuilder with setPrettyPrinting() and create() method.

Data Class object to JSON string

List to JSON string

Array to JSON string

Map to JSON string

Conclusion

Today we’re known how to parse JSON to Data Class, Array/List, Map in Kotlin, we also convert object to JSON String.

The steps can be summarized as:

  • Add Gson library
  • Define desired Class or Type (using TypeToken)
  • Use Gson.fromJson() or Gson.toJson() with Class or Type above
  • Use additional package GsonBuilder to get pretty JSON

You can also apply these methods to read and parse JSON file from assets in an Android Application.

Источник

How to parse JSON in Android using Kotlin

We’re going to parse JSON without using any 3rd party library, but using the java class JSONTokener.

With the JSONTokener, we can parse a JSON string into an object. These objects can be cast as JSONObject or as JSONArray. In that way, we’ll able to read the JSON values.

I’ll cover 3 cases that may you face when you’re trying to parse JSON:

  • Simple JSON: Just a simple JSON without any complex structure
  • Array JSON: The JSON structure begins with an array and without a key
  • Nested JSON: Includes nested objects

Simple JSON

A simple JSON doesn’t have any complex structure, like arrays, nested objects, e.t.c, and it looks like that:

After getting the response from the HTTP request, you parse the JSON string into JSONObject, to get the JSON values:

Array JSON

Sometimes, you might see a JSON start with an array and without having a key:

After getting the response, you parse the JSON string into a JSONArray and you’re looping through the array to get the JSON values.

Tip: If a key does not exist in some objects, you can set it as optional like this:
val >

Nested JSON

When a JSON object is inside another JSON object, it’s called ‘nested’, and will look like the following JSON structure:

After you get the response, you parse the JSON string into a JSONObject, then you get the “data” as a JSONArray, and you loop through the array.

If you have any questions, please feel free to leave a comment below

Источник

Kotlin Android – Read JSON file from assets using Gson

In this Kotlin-Android tutorial, I will show you how to read and parse JSON file from assets using Gson.

Where to put assets folder and JSON file

You will need to create the assets folder inside src/main, next to your java and res folder. Then make sure that your JSON file is within your assets folder.

For example, bezkoder.json file contains list of people data like this.

Create Data Class

Let’ create Person class with 3 fields: name, age, messages.

Create function for reading JSON file from assets

We’re gonna create a Utils class and add the function that will read JSON file from assets.

The function has 2 parameters: context & fileName .
– We get AssetManager object from context by context.assets , then use AssetManager.open() method to open a file in assets folder using ACCESS_STREAMING mode, it returns an InputStream .
– Then bufferedReader() creates a buffered reader on the InputStream and readText() helps us to read this reader as a String.

Parse JSON using Gson

Gson.fromJson() method

com.google.gson.Gson package provides fromJson() for deserializing JSON.

  • T : type of the desired object
  • json : could be a JsonElement object, a Reader object or a String
  • classOfT : class of T
  • typeOfT : specific genericized type

Add Gson to Android project

Gson is a Java/Kotlin library for converting JSON string to an equivalent Java/Kotlin object.
Open build.gradle file and add Gson library.

Parse JSON string to Kotlin object

In your activity, import Gson library and call getJsonDataFromAsset() .

Check Android Logcat, you can see:

In the code above, we use Gson.fromJson() method to parse JSON string to List

For more details about ways to parse JSON to Data Class object, to Array or Map , please visit:
Kotlin – Convert object to/from JSON string using Gson

Conclusion

Let me summarize what we’ve done in this tutorial:

  • put assets folder & JSON file in the right place
  • create data class corresponding to JSON content
  • use AssetManager to open the File, then get JSON string
  • use Gson to parse JSON string to Kotlin object

Источник

Serialization

Serialization is the process of converting data used by an application to a format that can be transferred over a network or stored in a database or a file. In turn, deserialization is the opposite process of reading data from an external source and converting it into a runtime object. Together they are an essential part of most applications that exchange data with third parties.

Some data serialization formats, such as JSON and protocol buffers are particularly common. Being language-neutral and platform-neutral, they enable data exchange between systems written in any modern language.

In Kotlin, data serialization tools are available in a separate component, kotlinx.serialization. It consists of two main parts: the Gradle plugin – org.jetbrains.kotlin.plugin.serialization and the runtime libraries.

Libraries

kotlinx.serialization provides sets of libraries for all supported platforms – JVM, JavaScript, Native – and for various serialization formats – JSON, CBOR, protocol buffers, and others. You can find the complete list of supported serialization formats below.

All Kotlin serialization libraries belong to the org.jetbrains.kotlinx: group. Their names start with kotlinx-serialization- and have suffixes that reflect the serialization format. Examples:

org.jetbrains.kotlinx:kotlinx-serialization-json provides JSON serialization for Kotlin projects.

org.jetbrains.kotlinx:kotlinx-serialization-cbor provides CBOR serialization.

Platform-specific artifacts are handled automatically; you don’t need to add them manually. Use the same dependencies in JVM, JS, Native, and multiplatform projects.

Note that the kotlinx.serialization libraries use their own versioning structure, which doesn’t match Kotlin’s versioning. Check out the releases on GitHub to find the latest versions.

Formats

kotlinx.serialization includes libraries for various serialization formats:

Note that all libraries except JSON serialization ( kotlinx-serialization-core ) are Experimental, which means their API can be changed without notice.

There are also community-maintained libraries that support more serialization formats, such as YAML or Apache Avro. For detailed information about available serialization formats, see the kotlinx.serialization documentation.

Example: JSON serialization

Let’s take a look at how to serialize Kotlin objects into JSON.

Before starting, you’ll need to configure your build script so that you can use Kotlin serialization tools in your project:

Apply the Kotlin serialization Gradle plugin org.jetbrains.kotlin.plugin.serialization (or kotlin(“plugin.serialization”) in the Kotlin Gradle DSL).

Add the JSON serialization library dependency: org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.1

Now you’re ready to use the serialization API in your code. The API is located in the the kotlinx.serialization package and its format-specific subpackages such as kotlinx.serialization.json .

First, make a class serializable by annotating it with @Serializable .

You can now serialize an instance of this class by calling Json.encodeToString() .

As a result, you get a string containing the state of this object in the JSON format:

You can also serialize object collections, such as lists, in a single call.

To deserialize an object from JSON, use the decodeFromString() function:

For more information about serialization in Kotlin, see the Kotlin Serialization Guide.

Источник

Parsing between JSON and Kotlin Object with Google Gson Library

Sazzad Hissain Khan

Jun 27, 2019 · 2 min read

In this tutorial I will discuss about how to parse a class object into json string and convert it back from json string to class object in Android Kotlin using popular Gson library.

Configuring Module: app/ build.gradle

To use the Gson library you need to add following dependency in your projects module gradle file ( Module: app/build.gradle) and re sync.

Let’s assume, we have a data class Student,

Parsing class object into json string

If you want to convert single hierarchical class object into equivalent json string you simply need to call Gson().toJson()

Parsing json string into class object

On the other hands , you can convert a json string into class object with below code. If you do not declare SerializedName (discussed in next section), your class field name should be same to json keys.

Customizing json keys while parsing

Sometimes server provided json keys are not neat and clean or not satisfactory with your project coding styles you follow. So you might want to make your data class field names non identical to json key names. You can do that with SerializedName annotation before each field.

Parsing nested json string to nested object

What if the json string is not of a simple single level object rather it also have nested json object? Let’s say some json string like below one?

In that case you can define nested classes and use them with Gson

Skipping nested hierarchy while parsing

Sometime you might want to skip deep down lower hierarchy of json object because it requires creating many small nested data classes. In that case one trick is to store lower level json objects as string in the parent class field. For example,

In the above json format if you don’t want to deal with city and post at that granular level so defining data class Address might be an overhead. You can simply store address object as a string in your student class. In that case you need to use JsonDeserializer .

Thus you can parse a nested hierarchical json object into a less hierarchical class object,

Similarly when we want to retrieve back the json string from the class object the specific field requires to be parsed directly from string representation to json object. In that case we use JsonSerializer.

To call this toJason() we need to use like,

Parsing between a Collection, List or Array

Gson is capable of parsing to and from an array or a list automatically into json object and vice versa. See the below code snippet,

Источник

Оцените статью