JSONObject和Gson用法详解

本文详细介绍了JSONObject和Gson的使用方法,包括所需jar包和常见应用场景。重点关注了使用这两种库将Json字符串转换为实体类时的注意事项,特别是Gson会将所有整数转化为浮点数的问题。

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

JSONObject和Gson用法详解

#

#

1.JSONObject使用方法详解

所需jar包

json-lib-2.4-jdk15.jar 
commons-beanutils-1.8.3.jar
commons-collections-3.2.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar

一般情况下除JSONObject的jar之外还需要依赖的其他5个jar包,如上所示

其中 JSONObject 目前最新的版本为2.4,其他版本下载地址为:http://sourceforge.net/projects/json-lib/files/json-lib/

常用的情景和实现方式

a.前台封装Json格式的数据后转成字符串(不包含复杂对象),后台用字符串接收,转成对应的类
  • 前台实现

    var params = {
        'page': 1,
        'rows': 10,
        'pickUpTmStr': '2017-09-15 15:00',
        'sendBackTmStr': '2017-09-16 15:00',
        'day': '1',
        'id': '123',
        'sortType': 1
    };
    $.ajax({
        type: "POST",
        url: "${ctx}/w/com/selectRentalCarForPage.json.json",
        data: {'paramsStr' : JSON.stringify(params)},
        dataType:'json',
        success: function(msg){
            if(msg.resultCode=="SUCCESS"){
                alert(msg.resultMessage);
            }else{
                closeAllDialog();
                alert(msg.resultMessage);
            }
        }
    });
    
  • 后台实现

    @RequestMapping(value = "/selectRentalCarForPage.json", method = RequestMethod.POST)
    public @ResponseBody IPageModule selectRentalCarForPage(HttpServletRequest request,HttpServletResponse response, 
        ModelMap model,String paramsStr) {
        IPageModule iPageModule =null;
        JSONObject jObjf = JSONObject.fromObject(paramsStr);
        Map<String,Object> paramsMap = (Map<String,Object>)JSONObject.toBean(jObjf, Map.class);
        try {   
            iPageModule = rentalCarService.selectRentalCarForPage(paramsMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return iPageModule;
    }
    

    此为将前台接收的参数转为Map,如需要转成实体类,则可以如下实现:

    JSONObject jObjf = JSONObject.fromObject(studentStr);
    Student student = (RentalCarIntent)JSONObject.toBean(jObjf, Student.class);
    

    注:若是将参数转为对应的实体类对象,前台封装参数时的key必须要与实体类中字段对应,否则会报错

b.前台封装Json格式的数据后转成字符串(不包含复杂对象),后台用字符串接收,转成对应的类
  • 前台实现

    var params = {
        'page': 1,
        'rows': 10,
        'pickUpTmStr': '2017-09-15 15:00',
        'sendBackTmStr': '2017-09-16 15:00',
        'day': '1',
        'id': '123',
        'sortType': 1
        'student':{
            'name':'小明',
            'sexCd':10
        }
    };
    $.ajax({
        type: "POST",
        url: "${ctx}/w/com/selectRentalCarForPage.json.json",
        data: {'paramsStr' : JSON.stringify(params)},
        dataType:'json',
        success: function(msg){
            if(msg.resultCode=="SUCCESS"){
                alert(msg.resultMessage);
            }else{
                closeAllDialog();
                alert(msg.resultMessage);
            }
        }
    });
    
  • 后台实现

    @RequestMapping(value = "/selectRentalCarForPage.json", method = RequestMethod.POST)
    public @ResponseBody IPageModule selectRentalCarForPage(HttpServletRequest request,HttpServletResponse response, 
        ModelMap model,String paramsStr) {
        IPageModule iPageModule =null;
        JSONObject jObjf = JSONObject.fromObject(paramsStr);
        classMap.put("student", Student.class);
        Map<String,Object> paramsMap = (Map<String,Object>)JSONObject.toBean(jObjf, Map.class,classMap);
        try {   
            iPageModule = rentalCarService.selectRentalCarForPage(paramsMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return iPageModule;
    }
    

    此为将前台接收的参数转为Map,如需要转成实体类,则可以如下实现:

    JSONObject jObjf = JSONObject.fromObject(studentStr);
    Student student = (Student)JSONObject.toBean(jObjf, Student.class);
    

    注:若是将参数转为对应的实体类对象,前台封装参数时的key必须要与实体类中字段对应,否则会报错,包括类中复杂对象名称,都要一一对应

    另注:classMap用法介绍

    /**字符串转java bean时,字符串中如果出现类似List , Map ,ArrayList、自定义的类型等复杂类型,解决方法如下:
    *1.Map<String, Class> classMap = new HashMap<String, Class>();
    *2.classMap.put("对象的那个特殊的属性名(集合)", 集合中的对象名.class);
    *3.最后加上一个参数(JudgementRestaurant)JSONObject.toBean(jObjf, JudgementRestaurant.class,classMap);
    */
    

2. Gson使用方法详解

所需jar包

gson-2.3.1.jar

常用的情景和实现方式

a.前台封装Json格式的数据后转成字符串(不包含复杂对象),后台用字符串接收,转成对应的类
  • 前台实现

    同上(与JSONObject封装方法一致)
    
  • 后台实现

    //代码基本一致,只是转换稍有不同
    JsonObject obj = (JsonObject)new Gson().fromJson(zhouStr, JsonObject.class);
    JudgementFleet judgementFleet = new Gson().fromJson(obj.get("fleet"), JudgementFleet.class);
    //或者
    JudgementFleet judgementFleet = (JudgementFleet)new Gson().fromJson(zhouStr, JudgementFleet.class);
    
    //list
    JSONObject jsonObject = JSONObject.fromObject(zhouStr);
    List<ProductDuty> productDutyList= (List<ProductDuty>)JSONArray.toCollection(jsonObject.getJSONArray("productDutyList"), ProductDuty.class);
    

重点发现

使用Json将字符串转换成实体类时,它会将所有的整数都变成浮点型,即所有的整数会加上’.0’,会导致后台判断出错,所以使用json的时候请格外注意,除此区别,没有复杂对象封装时,两者的转换效果是一样的

包含以下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、付费专栏及课程。

余额充值