Json convert to object with gjson.(Json 转换为类对象)

{"username":"mike chen", "status":"100", "totalCount":"5",
"itemArray":[ 
{"type":"CARDIO","description":"Running", "complete_value":"10", "unit":"minutes", "calories":"480"},
{"type":"CARDIO","description":"Swimming", "complete_value":"120", "unit":"minutes", "calories":"120"},
{"type":"CARDIO","description":"Walk", "complete_value":"120", "unit":"minutes", "calories":"180"},
{"type":"CARDIO","description":"Bike Riding", "complete_value":"120", "unit":"minutes", "calories":"280"},
{"type":"CARDIO","description":"Dog walking", "complete_value":"120", "unit":"minutes", "calories":"800"}
]}

将Json结构转换为如下对应的类对象。

public class ExerciseData {
	public String username = "";
	public int status = 0;
	public int totalCount = 0;
	public ArrayList <DiaryItem> itemArray;
	
	public class DiaryItem{
		public String type;
		public String description;
		public int complete_value;
		public String unit;
		public int calories;
	}}


可以使用gjson的转换功能,下面是一个转换类。可以在这里获得 gjson   https://code.google.com/p/google-gson/

package json;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;


public class JsonUtils {

    private static Gson sGson = new Gson();

    public static String jsonFromObject(Object object) {
        return sGson.toJson(object);
    }

    public static <T> T objectFromJson(String json, Class<T> clz) {
        return sGson.fromJson(json, clz);
    }

    public static<T> T objectFromJson(InputStream in, Class<T> clz) {
        try {
            JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
            T object = sGson.fromJson(reader, clz);
            reader.close();
            return object;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}


调用方法如下:

public static void ExerciseListParser (){
		try {
			InputStream is = new FileInputStream("exercise_json.txt");


			ExerciseData obj = JsonUtils.objectFromJson (is, ExerciseData.class);
			
			is.close();
			
			System.out.println ("-------------------json to object--------------------");
			obj.print();
			
			System.out.println ("-------------------object to json --------------------");
			System.out.println (JsonUtils.jsonFromObject(obj));


		} catch (IOException e) {
			e.printStackTrace();
		}
	}

Get the source code from here:
https://github.com/yuxiaohui78/android_develop/tree/master/JsonOperator


你可能感兴趣的:(Json convert to object with gjson.(Json 转换为类对象))