Using Kotlin JSON Parsing with Listview
In this post, we’ll learn how to parse JSON data using Moshi library.
What is Moshi?Moshi is an open source modern JSON library for both Android and Java, for parsing JSON. It is developed by Square (Jake and Jesse).It is like other JSON parsing libraries like Retrofit, GSON etc.
Step 1 :- Adding Internet permissions to manifest.xml as Fallows in red:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.ravi.jsonparseing"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Step 2 :- Adding Dependencies and Library to Gradle file(Module:app) as Fallows in red:
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 26 useLibrary 'org.apache.http.legacy' defaultConfig { applicationId "com.example.ravi.jsonparseing" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.0.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' compile 'com.squareup.moshi:moshi:1.5.0'}
Step 3 :- let’s create a model class add following code into it:
package com.example.ravi.jsonparseing /** * Created by ravi on 11/8/17. */internal class Product { val productid: String? = null val productname: String? = null val price: String? = null val instock: Int = 0 val offer: String? = null val color: String? = null val imageurl: String? = null}
Step 4 :- For JSON Data, we’ve added that
Apache
dependency into our gradle file. We’ll get web page content using an AsyncTask named DownloadWebPageTask
in our code.
Let’s see the code now:
import android.os.AsyncTask import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.ArrayAdapter import android.widget.ListView import com.squareup.moshi.Moshi import org.apache.http.client.methods.HttpGet import org.apache.http.impl.client.DefaultHttpClient import java.io.BufferedReader import java.io.InputStreamReader import java.util.* class MainActivity : AppCompatActivity() { internal var json = "" internal lateinit var list: ArrayList<Product> internal lateinit var listView: ListView internal lateinit var myList: ArrayList<String> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) DownloadWebPageTask().execute("http://api2.mytrendin.com/json/") } private inner class DownloadWebPageTask : AsyncTask<String, Void, String>() { override fun doInBackground(vararg urls: String): String { var response = "" for (url in urls) { val client = DefaultHttpClient() val httpGet = HttpGet(url) try { val execute = client.execute(httpGet) val content = execute.entity.content val buffer = BufferedReader(InputStreamReader(content)) var s = "" while (s != null) { s = buffer.readLine() response += s } } catch (e: Exception) { e.printStackTrace() } } return response } override fun onPostExecute(result: String) { json = result parseJSON(json) } } fun parseJSON(json: String) { Log.e("MainActivity","Result==>>"+json) val moshi = Moshi.Builder().build() val jsonAdapter = moshi.adapter<Array<Product>>(Array<Product>::class.java) var products: Array<Product>? = null myList = ArrayList<String>() try { products = jsonAdapter.fromJson(json) } catch (e: Exception) { e.printStackTrace() } for (p in products!!) { println(p.productid + " " + p.instock + " " + p.price + " " + p.color + " " + p.productname + " " + p.offer + " " + p.imageurl) myList.add("ID: " + p.productid + "\n" + "In stock: " + p.instock + "\n" + "Price: " + p.price + "\n" + "Color: " + p.color + "\n" + "Product name: " + p.productname + "\n" + "Offer: " + p.offer + "\n") } list = ArrayList(Arrays.asList(*products)) setUpListView() } fun setUpListView() { listView = findViewById<ListView>(R.id.listView) as ListView listView.adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, myList) } }
For Details about Moshi Library visit this link:https://www.mytrendin.com/parsing-json-using-moshi-library-android/ .
ReplyDelete