package com.example.gsontest02;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import com.example.entities.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getBasicToFromGson();
//getUserToFronGson();
getUserListToFromGson();
}
public void getBasicToFromGson() {
String[] nName = { "ㄱ", "ㄴ", "ㄷ", "ㄹ", "ㅁ", "ㅂ", "ㅅ", "ㅇ", "ㅈ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ" };
Gson gson = new Gson();
String result = gson.toJson(nName);
System.err.println("to gson : " + result);
String[] fromResult = gson.fromJson(result, String[].class);
for (String child : fromResult) {
System.err.println("fromGson : " + child);
}
}
public void getUserToFronGson() {
User user = new User();
user.setName("안드로이드");
user.setSex("boy");
user.setAge(3);
Gson gson = new Gson();
String toGsonResult = gson.toJson(user);
System.err.println(toGsonResult);
User userResult = gson.fromJson(toGsonResult, User.class);
System.err.println(userResult.getName());
System.err.println(userResult.getSex());
System.err.println(userResult.getAge());
}
public void getUserListToFromGson() {
List<User> users = new ArrayList<User>();
users.add(new User("태연", "girl", 24));
users.add(new User("택연", "boy", 26));
users.add(new User("박지성", "boy", 27));
users.add(new User("에일리", "girl", 22));
Gson gson = new Gson();
String userListResult = gson.toJson(users, ArrayList.class);
System.err.println(userListResult);
Type type = new TypeToken<List<User>>(){}.getType();
ArrayList<User> userListFromGson = gson.fromJson(userListResult, type);
for (User user : userListFromGson) {
System.err.println("userNmae : " + user.getName() + "userSex : " + user.getSex() + "userAge : " + user.getAge());
}
}
}
|