2014年6月24日 星期二

Android-Gson 簡單使用

使用Gson時,必須要先下載Google提供的Json編譯
下載點 : Gson

JSON 編譯網站 : 連結

在專案底下的lib放gson-2.2.1.jar檔案

在專案底Properties->Java Build Path->Libraries->Add JARs(同上行位置)

在專案底Properties->Java Build Path->Libraries->Order and Export ( gson打勾 )


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.gson.MainActivity"
    tools:ignore="MergeRootFrame" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

---------------------------------------------------------------------------------

User.java

package com.example.gson;

public class User {
private String username ;
private int errcode;
private int userId ;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getErrcode() {
return errcode;
}
public void setErrcode(int errcode) {
this.errcode = errcode;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}

}

---------------------------------------------------------------------------------

MainActivity.java

package com.example.gson;

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

import com.google.gson.Gson;

public class MainActivity extends Activity {
TextView textview01;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textview01 = (TextView) findViewById(R.id.textView1);

String jsonData = "{\"errcode\":888,\"username\":\"arthinking\",\"userId\":999}";
Gson gson = new Gson();
User user = gson.fromJson(jsonData, User.class);
textview01.setText(user.getErrcode()+"\n"+user.getUsername()+"\n"+user.getUserId());
}
}

----------------------------------------
[
  {
    "name":"Beagle",
    "colors":["black","white","tan"]
  },
  {
    "name":"Dalmation",
    "colors":["white","black"]
  }
]


class Dog {
  String name;
  String[] colors;
}

Gson gson = new Gson();
Dog[] dogs = gson.fromJson(input, Dog[].class);

資料來源 : http://blog.patrickbaumann.com/2011/11/gson-array-deserialization/

沒有留言:

張貼留言