Gson与JSONObject

本文探讨了Gson和JSONObject在处理JSON数据时的异同,包括使用场景、API接口、性能等方面。通过实例展示了如何将Java对象转换为JSON字符串,以及如何从JSON字符串反序列化回Java对象。对比分析表明,Gson在性能和简洁性上具有一定优势,而JSONObject则更易于理解和操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


package json;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.google.gson.Gson;

public class JsonExample {
	
	/**
	 * 使用Gson可以直接将实体类转化为json字符串
	 * @return
	 */
	public static String createJsonByGson() {
		HotelResponse hotelResponse = new HotelResponse();
		List<Hotel> hotelList = new ArrayList<Hotel>();
		Hotel hotel1 = new Hotel();
		Hotel hotel2 = new Hotel();
		Hotel hotel3 = new Hotel();
		Hotel hotel4 = new Hotel();
		hotel1.setHotelName("七天连锁酒店");
		hotel1.setAddress("长安街001号");
		hotel2.setHotelName("如家连锁酒店");
		hotel2.setAddress("长安街002号");
		hotel3.setHotelName("汉庭连锁酒店");
		hotel3.setAddress("长安街003号");
		hotel4.setHotelName("维多利亚连锁酒店");
		hotel4.setAddress("长安街004号");
		hotelList.add(hotel1);
		hotelList.add(hotel2);
		hotelList.add(hotel3);
		hotelList.add(hotel4);
		hotelResponse.setTotalRecords(999);
		hotelResponse.setPagesize(4);
		hotelResponse.setCurrpage(1);
		hotelResponse.setHotelList(hotelList);
		
		Gson gson = new Gson();
		String jsonStr = gson.toJson(hotelResponse);
		System.out.println("jsonStr = " + jsonStr);
		return jsonStr;
	}
	
	/**
	 * 使用Gson解析json串
	 */
	public static void praseJsonByGson() {
		String jsonStr = createJsonByGson();
		Gson gson = new Gson();
		HotelResponse hotelResponse = gson.fromJson(jsonStr, HotelResponse.class);
		int totalRecords = hotelResponse.getTotalRecords();
		int pagesize = hotelResponse.getPagesize();
		int currpage = hotelResponse.getCurrpage();
		List<Hotel> hotelList = hotelResponse.getHotelList();
		System.out.println("totalRecords = " + totalRecords);
	}
	
	/**
	 * 使用JSONObject可以直接将Map转化为json字符串	
	 * @return
	 */
	public static String createJsonByJSONObject() {
		JSONObject jo = new JSONObject();
		JSONArray ja = new JSONArray();
		Map<String, Object> map1 = new HashMap<String, Object>();
		Map<String, Object> map2 = new HashMap<String, Object>();
		Map<String, Object> map3 = new HashMap<String, Object>();
		Map<String, Object> map4 = new HashMap<String, Object>();
		map1.put("hotelName", "七天连锁酒店");
		map1.put("address", "长安街001号");
		map2.put("hotelName", "如家连锁酒店");
		map2.put("address", "长安街002号");
		map3.put("hotelName", "汉庭连锁酒店");
		map3.put("address", "长安街003号");
		map4.put("hotelName", "维多利亚连锁酒店");
		map4.put("address", "长安街004号");
		ja.add(map1);
		ja.add(map2);
		ja.add(map3);
		ja.add(map4);
		jo.put("totalRecords", 999);
		jo.put("pagesize", 4);
		jo.put("currpage", 1);
		jo.put("hotelList", ja);
		
		String jsonStr = jo.toString();
		System.out.println("jsonStr = " + jsonStr);
		return jsonStr;
	}
	
	/**
	 * 使用JSONObject解析json串
	 */
	public static void praseJsonByJSONObject() {
		String jsonStr = createJsonByJSONObject();
		JSONObject jo = JSONObject.fromObject(jsonStr);
		int totalRecords = jo.getInt("totalRecords");
		int pagesize = jo.getInt("pagesize");
		int currpage = jo.getInt("currpage");
		JSONArray ja =  jo.getJSONArray("hotelList");
		for(int i=0; i<ja.size(); i++) {
			String hotelName = ((JSONObject)ja.get(i)).getString("hotelName");
			System.out.println("hotelName = " + hotelName);
		}
		System.out.println("totalRecords = " + totalRecords);
	}
	
	public static void main(String[] args) {
		praseJsonByJSONObject();
	}
}

package json;

import java.util.List;

public class HotelResponse {
	private int totalRecords;
	private int pagesize;
	private int currpage;
	private List<Hotel> hotelList;
	
	public int getTotalRecords() {
		return totalRecords;
	}
	public void setTotalRecords(int totalRecords) {
		this.totalRecords = totalRecords;
	}
	public int getPagesize() {
		return pagesize;
	}
	public void setPagesize(int pagesize) {
		this.pagesize = pagesize;
	}
	public int getCurrpage() {
		return currpage;
	}
	public void setCurrpage(int currpage) {
		this.currpage = currpage;
	}
	public List<Hotel> getHotelList() {
		return hotelList;
	}
	public void setHotelList(List<Hotel> hotelList) {
		this.hotelList = hotelList;
	}
}

package json;

public class Hotel {
	private String hotelName;
	private String address;
	
	public String getHotelName() {
		return hotelName;
	}
	public void setHotelName(String hotelName) {
		this.hotelName = hotelName;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
}


包含以下java源文件: com.google.gson.DefaultDateTypeAdapter.class com.google.gson.ExclusionStrategy.class com.google.gson.FieldAttributes.class com.google.gson.FieldNamingPolicy.class com.google.gson.FieldNamingStrategy.class com.google.gson.Gson.class com.google.gson.GsonBuilder.class com.google.gson.InstanceCreator.class com.google.gson.JsonArray.class com.google.gson.JsonDeserializationContext.class com.google.gson.JsonDeserializer.class com.google.gson.JsonElement.class com.google.gson.JsonIOException.class com.google.gson.JsonNull.class com.google.gson.JsonObject.class com.google.gson.JsonParseException.class com.google.gson.JsonParser.class com.google.gson.JsonPrimitive.class com.google.gson.JsonSerializationContext.class com.google.gson.JsonSerializer.class com.google.gson.JsonStreamParser.class com.google.gson.JsonSyntaxException.class com.google.gson.LongSerializationPolicy.class com.google.gson.TreeTypeAdapter.class com.google.gson.TypeAdapter.class com.google.gson.TypeAdapterFactory.class com.google.gson.annotations.Expose.class com.google.gson.annotations.SerializedName.class com.google.gson.annotations.Since.class com.google.gson.annotations.Until.class com.google.gson.internal.ConstructorConstructor.class com.google.gson.internal.Excluder.class com.google.gson.internal.JsonReaderInternalAccess.class com.google.gson.internal.LazilyParsedNumber.class com.google.gson.internal.LinkedTreeMap.class com.google.gson.internal.ObjectConstructor.class com.google.gson.internal.Primitives.class com.google.gson.internal.Streams.class com.google.gson.internal.UnsafeAllocator.class com.google.gson.internal.bind.ArrayTypeAdapter.class com.google.gson.internal.bind.CollectionTypeAdapterFactory.class com.google.gson.internal.bind.DateTypeAdapter.class com.google.gson.internal.bind.JsonTreeReader.class com.google.gson.internal.bind.JsonTreeWriter.class com.google.gson.internal.bind.MapTypeAdapterFactory.class com.google.gson.internal.bind.ObjectTypeAdapter.class com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.class com.google.gson.internal.bind.SqlDateTypeAdapter.class com.google.gson.internal.bind.TimeTypeAdapter.class com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.class com.google.gson.internal.bind.TypeAdapters.class com.google.gson.reflect.TypeToken.class com.google.gson.stream.JsonReader.class com.google.gson.stream.JsonScope.class com.google.gson.stream.JsonToken.class com.google.gson.stream.JsonWriter.class com.google.gson.stream.MalformedJsonException.class
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值