Thursday 18 May 2017

1.Json Parsing with object

1.content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="#ab3400"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.nc.jsonparsing.MainActivity"
    tools:showIn="@layout/activity_main">
   <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView1"
    android:text="Amir"
    android:textSize="30dp"
    android:textStyle="bold"
    />
</RelativeLayout>

2.MainActivity.java

package com.example.nc.jsonparsing;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

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

public class MainActivity extends Activity {

    TextView textView1,textView2;
    String name;
    int id;
    public static final String ParsingData= "{\"employee\":{\"name\":\"amir\",\"salary\":56000,\"married\":false}}";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView1=(TextView)findViewById(R.id.textView1);
        try{
            JSONObject jsonObject=new JSONObject(ParsingData).getJSONObject("employee");
            String name= jsonObject.getString("name");
            int salary=jsonObject.getInt("salary");
            String status= jsonObject.getString("married");
            String str="Employee Name:"+name+"\nEmployee:"+salary+"\nstatus:"+status;
            textView1.setText(str);
        }
        catch(JSONException e)
        {
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

}

3 comments: