Android解析Json字符串和生成json字符串

直接写例子说明最清晰,使用google的GSON来搞定

1. 要被解析生成json字符串和从json字符串中获取生成的对象的类

package com.habby.test.test1;

class Person {
	int age;
	String name;
	Location[] locations;

	Person(int a, String nam, Location[] locations) {
		age = a;
		name = nam;
		this.locations = locations;
	}
}

class Location {
	String x1;
	int x2;
	
	public Location(String x1, int x2) {
		this.x1 = x1;
		this.x2 = x2;
	}
}
2. 解析/生成

package com.habby.test.test1;

import com.google.gson.Gson;

public class HabbyTest {
	
	public static void main(String[] args) {
		Location[] locations = new Location[3];
		for (int i = 0; i < 3; ++i) {
			locations[i] = new Location("Habby" + i + 1, i + 1);
		}
		
		Person person = new Person(100, "Mali", locations);
		
		// 把对象生成json字符串
		Gson gson = new Gson();
		String jsonObjString = gson.toJson(person); 
		System.out.println(jsonObjString);
		
		// 从json字符串中获取对象
		Person person2 = gson.fromJson(jsonObjString, Person.class);
		System.out.println("age = " + person2.age);
		System.out.println("name = " + person2.name);
		
		Location[] locations2 = person2.locations;
		for (int i = 0; i < locations2.length; ++i) {
			System.out.println("locatioin[].x1 = " + locations[i].x1);
			System.out.println("locatioin[].x2 = " + locations[i].x2);
		}
	}
}
3. 运行结果

{"age":100,"name":"Mali","locations":[{"x1":"Habby01","x2":1},{"x1":"Habby11","x2":2},{"x1":"Habby21","x2":3}]}
age = 100
name = Mali
locatioin[].x1 = Habby01
locatioin[].x2 = 1
locatioin[].x1 = Habby11
locatioin[].x2 = 2
locatioin[].x1 = Habby21
locatioin[].x2 = 3

讲的比较好:http://blog.csdn.net/lk_blog/article/details/7685169

http://blog.csdn.net/cyxlzzs/article/details/6646204

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值