码迷,mamicode.com
首页 > Web开发 > 详细

json与gson互转

时间:2015-05-21 14:14:47      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:android   文档   json   gson   android开发   

json与gson互转

导入gson.jar

bean:

public class Person {
    private String name;
    private int age;

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the age
     */
    public int getAge() {
        return age;
    }

    /**
     * @param age
     *            the age to set
     */
    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return name + ":" + age;
    }
}

Activity类

public class MainActivity extends Activity {

    private Button json;
    private Button gson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        json = (Button) findViewById(R.id.json);
        gson = (Button) findViewById(R.id.gson);

        json.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                // 对象转json
                Gson gson = new Gson();
                List<Person> persons = new ArrayList<Person>();
                for (int i = 0; i < 5; i++) {
                    Person p = new Person();
                    p.setName("name" + i);
                    p.setAge(i * 5);
                    persons.add(p);
                }
                String str = gson.toJson(persons);
                Log.d(TAG, "json==>>>" + str);
            }
        });

        gson.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                // json转对象
                Gson gson = new Gson();
                String str = "[{\"name\":\"xiaoming\",\"age\":22},{\"name\":\"xiaowang\",\"age\":0}]";
                List<Person> ps = gson.fromJson(str,
                        new TypeToken<List<Person>>() {
                        }.getType());
                for (int i = 0; i < ps.size(); i++) {
                    Person p = ps.get(i);
                    Log.d(TAG, "gson==>>>" + p.toString());
                }
                //Person person = gson.fromJson(str, Person.class);
                //Log.i(TAG, "gson==>>>" + person.toString());
            }
        });
    }

}

json与gson互转

标签:android   文档   json   gson   android开发   

原文地址:http://blog.csdn.net/menglele1314/article/details/45890537

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!