How to create Json Object using String in Android

In this android programming source code example, we are going to create Json Object using String in Android.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to create Json Object using String in Android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".json.Json8"
    android:layout_margin="16dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="JSON Object Using String"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:textColor="@color/colorAccent"
        android:id="@+id/text"/>

</LinearLayout>

MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.inducesmile.inducesmile_button.R;

import org.json.JSONException;
import org.json.JSONObject;

public class Json8 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json8);

        TextView jsonObjectTextview = findViewById(R.id.text);

        String jsonString = "{\n" +
                "\t\t\t\"Name\": \"Pascal Made Simple\",\n" +
                "\t\t\t\"price\": 700\n" +
                "\t\t}";

        //Creating JSONObject from String
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            jsonObjectTextview.setText(jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment