今天來講個關於"在Android中寫出JSON"(`・ω・´)+

JSON這個東西,如果有時常接觸串接API的人幾乎都會曉得

不知道的話...其實也沒關係XD~現在學就好

關於JSON,全名為JavaScript Object Notation

而其在程式語言中可使用String(字串)來存取

也就是說...JSON資料是可以整串資訊以String的方式儲存在SQLite或者其他你想存的地方

 

OK,那今天要來講述的是如何製作JSON資料

之前我有寫過一篇關於"如何串接網路資料解JSON"的文章

在這裡->碼農日常-『Android studio』取得網路資料(JSON格式)並以RecyclerView顯示列表

 

當時我是把網路上提供的API載下來,並且解開他的JSON資料後並顯示

今天剛好相反,我是要在畫面中取得輸入資料後再將這些資料轉為JSON(但是沒有把這些資料送到網路喔XD)(´・_・`)

 

因此,就來今天的範例吧

Gif_20200501201439695_by_gifguru

以及GitHub

->https://github.com/thumbb13555/JsonMakerExample

今天的內容將會從上面三個EditText中獲取資料,並輸出為JSON資料

為了證明我的JSON是正確的,我把我做出來的JSON丟到JSON的驗證軟體(゚д゚;)

->https://jsoneditoronline.org/#left=local.soqolu&right=local.witope

而結果是這樣

截圖 2020-05-01 下午8.54.18

 

OK,看理解的話就開始今天的內容(・ωー)~☆


 

1.認識JSON格式以及載入GSON的第三方庫

在製作JSON前我認為必須要了解JSON格式是怎麼做的(`・ω・´)+

我這邊直接了當地說:我覺得JSON格式就是ArrayList+HashMap的綜合體(笑)

 

ArrayList算是我最常用的陣列型態沒有之一

善用他的add()函式,搭配各種資料型態就可以玩出很多變化

另外就是HashMap資料型態,其特性就是

1.有一個index可以抓資料

2.index不會重複

 

因此仔細觀察JSON資料格式跟ArrayList<HashMap<String,String>>的話

就發現其實他們根本就是一樣的東西(・∀・)

JSON的相關介紹到這,我的重點是在闡述JSON格式跟ArrayList<HashMap<String,String>>之間的關聯性

 

好的在了解完JSON後,接著就是載入用來輔助轉換的第三方函式庫GSON

其載入庫在這邊->https://github.com/google/gson

GSON是由google所開發的專門拿來解JSON的輔助函式庫

也同時,他也能拿來製作JSON(´υ`)

 

那麼就來載入他的庫吧,請複製以下這串

implementation 'com.google.code.gson:gson:2.8.6'

 

找到build.grade

截圖 2020-05-01 下午10.33.38

 

點進去找到dependencies,並將這串加入

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.code.gson:gson:2.8.6'//使用GSON,來源->
    // https://github.com/google/gson
}

最後點下Sync Now即完成

截圖 2019-12-29 上午1.30.39

 

2.建立介面

這次要做的介面長這樣↓

截圖 2020-05-01 下午10.40.12

我其實猶豫很久到底要不要連同解JSON一起寫...

但後來是覺得,要連同解JSON的話又要寫RecyclerView做顯示...一來一往地會造成重點離題

所以再~~重申一次,如果想了解如何解JSON的話,請參考我這篇文章

o(メ・・)=日☆碼農日常-『Android studio』取得網路資料(JSON格式)並以RecyclerView顯示列表

所以除了上面收集資料外,下面就只有一個TextView作為顯示。

介面的程式碼長這樣,直接複製即可

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5" />

    <EditText
        android:id="@+id/editText_In01"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="25dp"
        android:layout_marginEnd="25dp"
        android:layout_marginBottom="16dp"
        android:ems="10"
        android:hint="請隨意輸入-1"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/editText2_In02"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/editText2_In02"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="25dp"
        android:layout_marginEnd="25dp"
        android:layout_marginBottom="16dp"
        android:ems="10"
        android:hint="請隨意輸入-2"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/editText3_In03"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <EditText
        android:id="@+id/editText3_In03"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="25dp"
        android:layout_marginEnd="25dp"
        android:ems="10"
        android:hint="請隨意輸入-3"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_Trans"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="轉換為JSON"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintEnd_toStartOf="@+id/guideline3"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText3_In03" />

    <TextView
        android:id="@+id/textView_Show"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        android:scrollbars="vertical"
        android:singleLine="false"
        android:text="此處顯示轉換的JSON字串"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/guideline" />

    <Button
        android:id="@+id/button_Clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="清除目前內容"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/guideline3"
        app:layout_constraintTop_toBottomOf="@+id/editText3_In03" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

3.撰寫主要內容

不囉唆,直接上全部程式

MainActivity.java

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EditText edIn01,edIn02,edIn03;
        Button btTrans,btClear;

        edIn01 = findViewById(R.id.editText_In01);
        edIn02 = findViewById(R.id.editText2_In02);
        edIn03 = findViewById(R.id.editText3_In03);
        btTrans = findViewById(R.id.button_Trans);
        btClear = findViewById(R.id.button_Clear);

        ArrayList<HashMap<String,String>> arrayList = new ArrayList<>();//先建立一個ArrayList包HashMap

        btClear.setOnClickListener((v)->{
            arrayList.clear();
        });

        btTrans.setOnClickListener((v -> {
            String first,second,third;
            first = edIn01.getText().toString();
            second = edIn02.getText().toString();
            third = edIn03.getText().toString();
            if (first.length() == 0||second.length() == 0||third.length() == 0) return;
            HashMap<String,String> hashMap = new HashMap<>();//新增一個HashMap
            hashMap.put("MyFirstHashIndex",first);
            hashMap.put("MySecondHashIndex",second);
            hashMap.put("MyThirdHashIndex",third);
            arrayList.add(hashMap);//包裹進內容後,將HashMap放進ArrayList

            String gson = new Gson().toJson(arrayList);//將此ArrayList轉為json字串
            TextView tvShow = findViewById(R.id.textView_Show);
            tvShow.setMovementMethod(ScrollingMovementMethod.getInstance());//使TextView可以捲動
            gson = gson.replace("[","[\n");
            gson = gson.replace("]","]\n");
            gson = gson.replace("{","\t{\n\t");
            gson = gson.replace("}","\n\t}\n");
            gson = gson.replace(",",",\n\t");

            tvShow.setText(gson);//show出Json字串
        }));
    }//onCreate
}

 

整體的重點

 

1.在外層建立一個ArrayList

ArrayList<HashMap<String,String>> arrayList = new ArrayList<>();

 

2.(點擊事件內)取得三個EditText的內容,並偵測是否有空值(PS.有空值是不會造成閃退的,只是我爽XD)

String first,second,third;
first = edIn01.getText().toString();
second = edIn02.getText().toString();
third = edIn03.getText().toString();
if (first.length() == 0||second.length() == 0||third.length() == 0) return;

 

3.(點擊事件內)新增一個HashMap,並將資料輸入HashMap

HashMap<String,String> hashMap = new HashMap<>();//新增一個HashMap
hashMap.put("MyFirstHashIndex",first);
hashMap.put("MySecondHashIndex",second);
hashMap.put("MyThirdHashIndex",third);

 

4.(點擊事件內)最後將資料包進最一開始的ArrayList內

arrayList.add(hashMap);//包裹進內容後,將HashMap放進ArrayList

 

5.(點擊事件內)將ArrayList轉為JSON字串

String gson = new Gson().toJson(arrayList);//將此ArrayList轉為json字串

 

基本上程式不多,但蘊藏了大道理( ´_ゝ`)

此時按下執行,就能看見想要的效果囉(´・з・)


 

結語

這八成又是人氣會低的文章(笑)

 

我是不知道其他人的運用如何,但對我而言,這是我工作中常用的東西

JSON格式最經典的就是他可以運用字串格式傳送大量的設定內容

我個人的應用是將像是手機個人設定,或者針對某硬體的參數設定作儲存

而這些資料會可以被保存在SQLite內,之後就能快速拿來載入等等

 

雖然今天的文章又是個冷門的東西,但是希望能對各位有幫助。d(>_・ )

thank-you-lebron-memes

arrow
arrow

    碼農日常 發表在 痞客邦 留言(3) 人氣()