Parsing using JSONObject

1, JSON data

  1. JSON string access method:

    2. Introduction

– JSON(JavaScript Object Notation) is a lightweight data exchange format.

– writing format of JSON data:

                " KEY " : " VALUE "

There are two types of JSON structures:

         1. Object (a column of the table): the object is represented in js as the content enclosed by "{}", and the data structure is a collection of key value pairs of {key: value,key: value,...}.

         2. Array (the whole table): the array is enclosed by brackets "[]" in js, and the data structure is ["java","javascript","vb",...]. The value method is the same as that in all languages. It is obtained by index. The types of field values can be numbers, strings, arrays and objects.

example:

    Object:

    Array:

2, JSONObject

  1. Introduction

         JSONObject is a data structure, which can be understood as a JSON format data structure (key value structure). It is an important data transmission object. You can use the put method to add elements to the objects of JSONObject class.

  2. Add method

JSONObject jsonObject = new JSONObject();
jsonObject.put("id", 1);
jsonObject.put("name", "Zhang San");
jsonObject.put("sex","M");
jsonObject.put("age", 19);
jsonObject.put("major", new String[] {"Programming","artificial intelligence"});
System.out.println(jsonObject.toString());

HashMap<String,Object> hashMap = new HashMap<>( );
hashMap.put("id", 1);
hashMap.put("name", "Zhang San");
hashMap.put("sex","M");
hashMap.put("age", 19);
hashMap.put("major", new String[] {"Programming","artificial intelligence"});
System.out.println(new JSONObject(hashMap).toString());

User user = new User();
user.put("id", 1);
user.put("name", "Zhang San");
user.put("sex","M");
user.put("age", 19);
user.put("major", new String[] {"Programming","artificial intelligence"});
System.out.println(new JSONObject(user));

         It can be seen that JSONObject can easily convert other objects into JSONObject objects, and it can also convert the string data received by the network into JSONObject objects.

String str = "{\"Number\":\"G14060101\",\"Name\":\"Zhang San\",\"Sex\":\"female \",\"Age\":20}";
JSONObject jsonObject = new JSONObject( str ); //str is passed in as a parameter

  3. Parsing JSON formatted strings using JSONObject

    (1) Common methods provided by JSONObject class

functionexplain
JSONObject()            Create an empty JSONObject object
getJSONObject(String key)     Get the corresponding JSONObject object according to the key
getJSONArray(String key)Get the corresponding JSONObject array according to the key
get(String key)Obtain the corresponding value value in the JSONObject Object according to the key value. The returned Object is the Object object and needs to be manually converted to the required data type
toString()Converts a JSONObject object to a string in json format

  

    (2) Examples

                 Suppose that the result returned from the server is a string in JSON format, as shown in the following figure

  Demand 1: get the current weather information of Shenzhen

         It can be found from the returned data that the current weather information is stored in the area with the index "data", and the data under the data area needs to be obtained through the getJSONObject() method.

//Create a JSONObject object based on the returned string
JSONObject jsonObject = new JSONObject(str);
JSONObject jsonData = jsonObject.getJSONObject("data");
//Then, read the value through the getString() method
String jsonTemplow = jsonData.getString("templow");
String jsonTempHigh = jsonData.getString("temphigh");
String jsonWeather = jsonData.getString("weather");
String jsonTempnow = jsonData.getString("tempnow");

Demand 2: get the current index reminders of Shenzhen

          It can be found from the returned data that all index reminders are stored in the JSON array with index "index", which needs to be operated through the jsonArray class. Then, the data in jsonArray is parsed by classification and stored in different ArrayList arrays, named names, levels, msgs, etc.

//Create a JSONObject object based on the returned string
JSONObject jsonObject = new JSONObject(str);
JSONObject jsonData = jsonObject.getJSONObject("data");
JSONArray jsonArray = jsonData.getJSONArray("index");
List<String> names = new ArrayList<String >();
List<String> levels = new ArrayList<String >();
List<String> msgs = new ArrayList<String >();
for (int i=0;i<jsonArray.length();i++){
     JSONObject partIndex = jsonArray.getJSONObject(i);
     String name = partIndex.getString("name");
     names.add(name);
     String level = partIndex.getString("level");
     levels.add(level);
     String msg = partIndex.getString("msg");
     msgs.add(msg);
}

Project implementation: "aggregate data" weather API

http://v.juhe.cn/weather/index?format=2&cityname= City name & KEY = the KEY you applied for

  Note: before using this interface, the user needs to register and obtain the corresponding secret KEY

Postman software

3, Code part

  1,activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

  2,MainActivity.java

package com.example.zsjsonobject;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    //1. Define a string variable to store the network address of the HTTP request
    public static final String address = "http://v.juhe.cn/weather/index?format=2&cityname=%E8%8B%8F%E5%B7%9E&key=ccfadb3491e63c1c3556f3ceb19e1237";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //2. Call the sendOkHttpRequest() method of the tool class to obtain the weather information returned by the server
        HttpUtil.sendOkHttpRequest(address,new okhttp3.Callback(){

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    //Get the data returned by the server
                String responseData = response.body().string();
                //It can be found through Postman that the weather information of the next 7 days is stored in the JSON array with the index value of future
                try{
                    JSONObject jsonObject = new JSONObject(responseData);
                    JSONObject jsonData = jsonObject.getJSONObject("result");
                    JSONArray jsonArray = jsonData.getJSONArray("future");
                    for(int i=0;i<jsonArray.length();i++)
                    {
                        JSONObject partFuture = jsonArray.getJSONObject(i);
                        String temperature = partFuture.getString("temperature");
                        String weather = partFuture.getString("weather");
                        String wind = partFuture.getString("wind");
                        String week = partFuture.getString("week");
                        String date = partFuture.getString("date");
                        Log.d("MainActivity","temperature:"+temperature+" "+"weather:"+weather+" "+"wind:"+wind+" "+"week:"+week+" "+"date:"+date);
                    }

                }catch (Exception e){

                }

            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }
        });
    }
}

  3,HttpUtil.java

v

package com.example.zsjsonobject;

import okhttp3.OkHttpClient;
import okhttp3.Request;

public class HttpUtil {
    public static void sendOkHttpRequest(String address,okhttp3.Callback callback){
        //The asynchronous request mode of okHttp framework is used to complete data fetching
        //1. Obtain the instance of OkHttpClient class
        OkHttpClient client = new OkHttpClient();

        //2. Create a Request object and set the target network address, Request method, etc. through the attribute
        Request request = new Request.Builder()
                        .url(address)   //Pass the first parameter into the url property
                        .build();
        //3. Call the newCall() method through the instance of OkHttpClient class to create a call object, and send the result of asynchronous request to the callback interface
        client.newCall(request).enqueue(callback);

    }
}

Tags: Java Android JSON

Posted on Mon, 13 Sep 2021 15:57:10 -0400 by Adrianc333