Read json from file android

Android — How to Read and Write (Parse) data from JSON File ?

Mar 15, 2020 · 4 min read

How to Insert, Update and Delete the data available in JSON File in Android ?

Android provides several ways of dealing with app data within the system or local storage. We are going to be dealing with app-specific storage of data in directory available in Internal or External Storage of system.

  • Internal Storage : Sensitive data, No other application access it.
  • External Storage : Other application can access it like Images.

What we are going to do ?

We will generate a JSON file, which will be stored in Internal storage of application. From android application user will add( WRITE) data, which will be converted into JSON format(JSON Object) and then stored in JSON file.

We w i ll access( READ) the data from JSON file and converted into app usable format like string, arrays etc.

We will also UPDATE the data from JSON file and save it back to JSON file.

We will also perform the DELETION operation on JSON file data/Objects.

Data will be taken in terms of Java Object and transferred to JSON File.

Источник

Java Android – Read JSON file from assets using Gson

In this Java-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, together with java and res folder. Then put JSON file inside assets folder.

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

Create Java Data Class

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

Create function for reading JSON file from assets

Let’s a Utils class and add a static function that will read JSON file from assets.

Читайте также:  Сбербанк определитель номера android

You can see that getJsonFromAssets() 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 we use InputStream.read() to read data into byte[] buffer and readText() to transform the buffer into 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 library for converting JSON string to an equivalent Java object.
Open build.gradle file and add Gson library.

Parse JSON string to Java object

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

Now, open Android Logcat window and you can see:

Conclusion

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

Источник

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

Читайте также:  This is the police для android

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

Источник

How to Read and Write JSON data in Kotlin with GSON

Kotlin is now official language for Android development and it is well support in Android Studio. So here in this tutorial we are going to learn about how to read and write GSON data in Kotlin. If you would like learn the java version of this tutorial check out the last tutorial “How to Read and Write JSON data using GSON”.

Introduction

In this tutorial we will write two method. In first method we will create a JSON file and in second method we will read the file and and print in a text box. If you like to know more about the basic entity of JSON you can checkout Basic JSON entity here.

JSON file sample for this Kotlin Tutorial

Create the POJO class in Kotlin

You must created and implement the POJO class earlier in Java. Here we will create a POJO class in Kotlin as given below.

In above example of POJO class did you notice something? If don’t then let me explain you. In Kotlin we don’t required a Getter and Setter method to set and get the details of the object. Simply you can refer using the variable as like local variable of the class.

In above example we are just using the postHeading variable using “.” operator. We don’t need to create a method like below to retrieve the value of variable.

Write JSON data in Kotlin from file

For writing the JSON data to file in Kotlin, we need to deal with file handling to write the file into file. In this example we are creating the file into cache location. So that it should be get deleted whenever required by system. If you want you create at some different location as well, but make sure to add the appropriate permission to write on storage.

We required a list to store the all tag list as defined in our sample JSON file. So using below code we will create the List of String type in kotlin and add some value into tags List.

Did you know what is difference between var and val in Kotlin? If don’t let me explain you, if you declare a variable as var then value of variable can be change, but if declare as val you can’t change the value later.

Читайте также:  Лучшие менеджеры файлов для android

Create a Object of Post

Create a Object of Gson

Convert the Json object to JsonString

Initialize the File Writer and write into file

Complete code to write JSON data in Kotlin

Below method will take filename as input and write the JSON data into the file.

Reading JSON data in Kotlin

Reading the data from JSON file is also not so complicated. We have to follow some simple steps for this.

First of all create a local instance of gson using the below code.

Read the PostJSON.json file using buffer reader.

Read the text from buffferReader and store in String variable.

Convert the Json File to Gson Object in Kotlin

Store the data in String Builder in kotlin

Display the all Json object in text View

Complete code of read JSON data in Kotlin

This method will take the filename as input and display the content in textbox.

Safe Call in Kotlin

You may have notice that we use “?.” many time in code. In Kotlin it is called Safe Call operator we use this where we think that null value can comes as input or value change to null. So kotlin is well designed to handle the null pointer exception. Check this like to learn more about the Safe Call in Kotlin.

Complete MainActivity.kt

After you implement this you will get the similar output as given in the screen shots.

If you have any further query or question then please put your question in the comment section below.

Источник

Учебник по JSON для Android: создание и анализ данных JSON

В этом руководстве описывается, как использовать JSON с Android . JSON расшифровывается как (Java Script Object Notation). Это простой и легкий формат обмена данными, который может быть легко прочитан людьми и машинами. JSON — это текстовый формат, не зависящий от языка. Он представляет данные в текстовом формате, чтобы их можно было легко проанализировать.

Введение в JSON

JSON использует две разные структуры:

  • Коллекция пары имя / значение
  • массив

Первую структуру можно использовать для моделирования объекта, поскольку объект представляет собой набор атрибутов, которые содержат некоторые значения. Массив может использоваться для моделирования списка, массива объектов и так далее. Таким образом, используя эти две структуры, мы можем передавать данные между двумя машинами простым и эффективным способом. В последнее время JSON пользуется большим успехом, и большинство доступных API поддерживает формат JSON. Давайте посмотрим, как мы можем представлять данные в формате JSON.

Объект в JSON моделируется с помощью , а его атрибуты можно моделировать с помощью name: value pair.Value, в свою очередь, может быть объектом, массивом или «простым» значением, например, примитивным значением (int, Строка, логическое значение и т. Д.).

Так что если у нас есть, например, класс Java, как:

Источник

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