转自:http://www.stormzhang.com/android/2014/05/22/android-gson/
Json格式化校验工具:kjson
Gson的官方下载地址:google-gson
导入Gson包
复制gson-2.4.jar到UseGson\app\libs
AndroidStudio右键gson-2.4.jar -> add as library
会自动在app/build.gradle里
dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:appcompat-v7:22.1.1' compile files('libs/gson-2.4.jar') }
单个对象
假设Json的数据格式是这样:
{ "id": 100, "body": "It is my post", "number": 0.13, "created_at": "2014-05-22 19:12:38" }
public class Foo { public int id; public String body; public float number; public String created_at; }
created_at不是java风格,java编程规范是驼峰结构,Gson很人性化的也提供注解的方式,只需要把Foo对象改成:
public class Foo { public int id; public String body; public float number; @SerializedName("created_at") public String createdAt; }
public static final String JSON_DATA = "..."; Foo foo = new Gson().fromJson(JSON_DATA, Foo.class);
这里created_at直接定义了String类型,如果想要Data类型也可以:
public class Foo { public int id; public String body; public float number; public Date created_at; } public static final String JSON_DATA = "..."; GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss"); Gson gson = gsonBuilder.create(); Foo foo = gson.fromJson(JSON_DATA, Foo.class);
对象的嵌套
假设Json的数据格式是这样:
{ "id": 100, "body": "It is my post", "number": 0.13, "created_at": "2014-05-22 19:12:38", "foo2": { "id": 200, "name": "haha" } }
那么定义的对象是这样:
public class Foo { public int id; public String body; public float number; public String created_at; public ChildFoo foo2; public class ChildFoo { public int id; public String name; } }
对象数组
json数组:
[{ "id": 100, "body": "It is my post1", "number": 0.13, "created_at": "2014-05-20 19:12:38" }, { "id": 101, "body": "It is my post2", "number": 0.14, "created_at": "2014-05-22 19:12:38" }]
这种解析有两种方法:
1. 解析成数组
public static final String JSON_DATA = "..."; Foo[] foos = new Gson().fromJson(JSON_DATA, Foo[].class); // 这时候想转成List的话调用如下方法 // List<Foo> foosList = Arrays.asList(foos);
public static final String JSON_DATA = "..."; Type listType = new TypeToken<ArrayList<Foo>>(){}.getType(); ArrayList<Foo> foos = new Gson().fromJson(JSON_DATA, listType);
1. 添加Gson包
复制gson-2.4.jar到UseGson\app\libs
AndroidStudio右键gson-2.4.jar -> add as library
2. app\src\main\assets
singleObject (new时选择Json格式)
{ "id": 100, "body": "It is my post", "number": 0.13, "created_at": "2015-10-09 14:12:30" }
{ "id": 100, "body": "It is my post", "number": 0.13, "created_at": "2014-05-22 19:12:38", "child": { "id": 200, "name": "haha" } }
[{ "id": 100, "body": "It is my post1", "number": 0.13, "created_at": "2014-05-20 19:12:38" }, { "id": 101, "body": "It is my post2", "number": 0.14, "created_at": "2014-05-22 19:12:38" }]
3. 对应的类
SingleObject.java
package com.silion.usegson; import com.google.gson.annotations.SerializedName; /** * Created by silion on 2015/10/9. */ public class SingleObject { public int id; public String body; public float number; //public String created_at; @SerializedName("created_at") public String createdAt; public String toString() { return "SingleObject id = " + id + ", body = " + body + ", number = " + number + ", createdAt = " + createdAt; } }
package com.silion.usegson; import java.util.Date; /** * Created by silion on 2015/10/9. */ public class SingleObjectData { public int id; public String body; public float number; public Date created_at; public String toString() { return "SingleObjectData id = " + id + ", body = " + body + ", number = " + number + ", created_at = " + created_at; } }
package com.silion.usegson; /** * Created by silion on 2015/10/9. */ public class NestedObject { public int id; public String body; public float number; public String created_at; public Child child; public class Child { public int id; public String name; } public String toString() { return "NestedObject id = " + id + ", body = " + body + ", number = " + number + ", createdAt = " + created_at + "\n" +"child = " + this.child.id + ", " + this.child.name; } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" 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:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/single" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/single" /> <Button android:id="@+id/nested" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/nested" /> <Button android:id="@+id/array" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/array" /> </LinearLayout>
package com.silion.usegson; import android.app.Activity; import android.content.res.AssetManager; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MainActivity extends Activity { View.OnClickListener mClickListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.single: { AssetManager assetManager = MainActivity.this.getAssets(); try { SingleObject object = new Gson().fromJson(new InputStreamReader(assetManager.open("singleObject")), SingleObject.class); android.util.Log.v("slong.liang", object.toString()); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setDateFormat("yyyy-mm-dd HH:mm:ss"); SingleObjectData objectData = gsonBuilder.create().fromJson(new InputStreamReader(assetManager.open("singleObject")), SingleObjectData.class); android.util.Log.v("slong.liang", objectData.toString()); } catch (IOException e) { e.printStackTrace(); } break; } case R.id.nested: { AssetManager assetManager = MainActivity.this.getAssets(); Reader json = null; try { InputStream is = assetManager.open("nestedObject"); json = new InputStreamReader(is); } catch (IOException e) { e.printStackTrace(); } NestedObject object = new Gson().fromJson(json, NestedObject.class); android.util.Log.v("slong.liang", object.toString()); break; } case R.id.array: { AssetManager assetManager = MainActivity.this.getAssets(); Reader json1 = null; try { json1 = new InputStreamReader(assetManager.open("arrayObject")); } catch (IOException e) { e.printStackTrace(); } //解析成数组 Gson gson = new Gson(); SingleObject[] objects = gson.fromJson(json1, SingleObject[].class); List<SingleObject> objectList1 = Arrays.asList(objects); android.util.Log.v("slong.liang", "-------Array method 1--------"); for(SingleObject object : objectList1) { android.util.Log.v("slong.liang", object.toString()); } Reader json2 = null; try { json2 = new InputStreamReader(assetManager.open("arrayObject")); } catch (IOException e) { e.printStackTrace(); } //解析成List Type listType = new TypeToken<ArrayList<SingleObject>>(){}.getType(); List<SingleObject> objectList2 = gson.fromJson(json2, listType); android.util.Log.v("slong.liang", "-------Array method 2--------"); for(SingleObject object : objectList2) { android.util.Log.v("slong.liang", object.toString()); } break; } default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button singleButton = (Button) findViewById(R.id.single); singleButton.setOnClickListener(mClickListener); Button nestedButton = (Button) findViewById(R.id.nested); nestedButton.setOnClickListener(mClickListener); Button arrayButton = (Button) findViewById(R.id.array); arrayButton.setOnClickListener(mClickListener); } }