JSONUtil

/**
 *
 * Copyright (c) 2014 CoderKiss
 *
 * CoderKiss[AT]gmail.com
 *
 */

package com.kisstools.utils;

import java.math.BigDecimal;
import java.util.Set;

import android.os.Bundle;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class JSONUtil {
   public static final String TAG = "JSONUtil";

   public static boolean isJSON(String value) {
      if (TextUtils.isEmpty(value)) {
         return false;
      }

      try {
         JSON.parse(value);
      } catch (Exception e) {
         return false;
      }
      return true;
   }

   public static JSON parseJSON(String value) {
      if (TextUtils.isEmpty(value)) {
         return null;
      }

      JSON jo = null;
      try {
         jo = (JSON) JSON.parse(value);
      } catch (Exception e) {
      }
      return jo;
   }

   public static boolean isJSONObject(String value) {
      if (TextUtils.isEmpty(value)) {
         return false;
      }

      try {
         JSON.parseObject(value);
      } catch (Exception e) {
         return false;
      }
      return true;
   }

   public static JSONObject parseObject(String value) {
      if (TextUtils.isEmpty(value)) {
         return null;
      }

      JSONObject jo = null;
      try {
         jo = JSON.parseObject(value);
      } catch (Exception e) {
      }
      return jo;
   }

   public static boolean isJSONArray(String value) {
      if (TextUtils.isEmpty(value)) {
         return false;
      }

      try {
         JSON.parseArray(value);
      } catch (Exception e) {
         return false;
      }
      return true;
   }

   public static JSONArray parseArray(String value) {
      if (TextUtils.isEmpty(value)) {
         return null;
      }

      JSONArray ja = null;
      try {
         ja = JSON.parseArray(value);
      } catch (Exception e) {
      }
      return ja;
   }

   public static boolean isEmpty(JSONObject jo) {
      if (jo == null || jo.isEmpty()) {
         return true;
      } else {
         return false;
      }
   }

   public static boolean isEmpty(JSONArray ja) {
      if (ja == null || ja.isEmpty()) {
         return true;
      } else {
         return false;
      }
   }

   public static String getString(JSONObject params, String key) {
      return getString(params, key, "");
   }

   private static String getString(JSONObject params, String key, String df) {
      if (df == null) {
         df = "";
      }
      return getValue(params, key, df);
   }

   public static boolean getBoolean(JSONObject params, String key, boolean df) {
      return getValue(params, key, df);
   }

   public static int getInt(JSONObject params, String key) {
      return getInt(params, key, 0);
   }

   public static int getInt(JSONObject params, String key, int df) {
      return getValue(params, key, df);
   }

   public static JSONObject getJSONObject(JSONObject params, String key) {
      return getJSONObject(params, key, null);
   }

   public static JSONObject getJSONObject(JSONObject params, String key,
         JSONObject df) {
      if (df == null) {
         df = new JSONObject();
      }
      return getValue(params, key, df);
   }

   @SuppressWarnings("unchecked")
   public static <T> T getValue(JSONObject params, String key, T df) {
      if (params == null || params.isEmpty()) {
         return df;
      }
      if (df == null) {
         return df;
      }

      if (!params.containsKey(key)) {
         return df;
      }

      T value = df;
      Object obj = params.get(key);
      if (obj != null && value.getClass().isAssignableFrom(obj.getClass())) {
         value = (T) obj;
      } else {
         LogUtil.w(TAG, "[key] " + key + " [value] " + obj);
      }
      return value;
   }

   public static JSONObject toJSONObject(Bundle bundle) {
      JSONObject joBundle = new JSONObject();
      if (bundle == null) {
         return joBundle;
      }

      Set<String> keys = bundle.keySet();
      for (String key : keys) {
         Object value = bundle.get(key);
         joBundle.put(key, value);
      }
      return joBundle;
   }

   public static Bundle toBundle(JSONObject params) {
      return toBundle(null, params);
   }

   public static Bundle toBundle(Bundle bundle, JSONObject params) {
      if (bundle == null) {
         bundle = new Bundle();
      }

      if (params == null || params.isEmpty()) {
         return bundle;
      }

      for (String key : params.keySet()) {
         Object value = params.get(key);
         if (value instanceof Integer) {
            bundle.putInt(key, (Integer) value);
         } else if (value instanceof Boolean) {
            bundle.putBoolean(key, (Boolean) value);
         } else if (value instanceof String) {
            bundle.putString(key, (String) value);
         } else if (value instanceof Long) {
            bundle.putLong(key, (Long) value);
         } else if (value instanceof Double) {
            bundle.putDouble(key, (Double) value);
         } else if (value instanceof Float) {
            float f = (Float) value;
            BigDecimal bd = new BigDecimal(Float.toString(f));
            double dd = bd.doubleValue();
            bundle.putDouble(key, dd);
         } else if (value instanceof JSON) {
            String jsonStr = ((JSON) value).toJSONString();
            bundle.putString(key, jsonStr);
         }
      }

      return bundle;
   }
}
<think>好的,我现在要回答用户关于Hutool库中JSONUtil工具类的功能和用法的问题。首先,我需要回忆Hutool的文档内容,特别是JSONUtil的相关部分。记得JSONUtil主要是简化JSON操作,比如对象转JSON字符串、解析JSON等。 接下来,用户需要具体的功能和使用方法,所以我要列出主要功能点,比如序列化、反序列化、格式化等。同时,用户提到的例子中有JsonUtil,但Hutool中正确的类名是JSONUtil,可能需要指出这一点,避免混淆。 然后,要确保每个功能点都有对应的代码示例,比如使用toJsonStr方法将对象转为JSON字符串,用parseObj解析JSON对象。还要注意代码的正确性,比如处理日期可能需要自定义格式,或者使用不同的解析选项。 用户可能还会关心如何读取和写入JSON文件,这部分需要包含文件操作的示例,比如readJSONObject和writeJSON方法。此外,格式化输出也是一个常见需求,要展示如何使用toJsonPrettyStr美化JSON。 需要注意引用用户提供的参考内容,其中提到了Prop工具类,但当前问题集中在JSONUtil,所以引用标识要正确对应。最后,生成相关问题时要围绕JSON处理的其他方面,比如异常处理、性能优化、其他工具类对比等,帮助用户扩展了解。 整个过程中,要确保使用正确的中文表达,LaTeX格式正确,没有行内公式,独立公式用$$...$$。同时,检查代码块是否使用正确的语法高亮,比如Python示例中的代码结构是否正确。最后,确保回答结构清晰,分点说明,并自然融入引用标记。</think>### Hutool JSONUtil 功能及使用方法详解 Hutool的$JSONUtil$是JSON处理工具类,提供了简化JSON序列化与反序列化的方法,以下是核心功能及示例: --- #### 一、核心功能 1. **对象与JSON互转** ```java // 对象转JSON字符串 User user = new User("张三", 25); String jsonStr = JSONUtil.toJsonStr(user); // {"name":"张三","age":25} // JSON字符串转对象 User parsedUser = JSONUtil.toBean(jsonStr, User.class); ``` 2. **JSON解析与构建** ```java // 解析JSON对象 JSONObject jsonObj = JSONUtil.parseObj("{\"key\":\"value\"}"); String value = jsonObj.getStr("key"); // "value" // 动态构建JSON JSONObject newObj = JSONUtil.createObj() .set("id", 1001) .set("status", true); ``` 3. **日期格式化处理** ```java // 自定义日期格式 JSONUtil.toJsonStr(user, new JSONConfig().setDateFormat("yyyy-MM-dd")); ``` 4. **JSON文件读写** ```java // 读取JSON文件 JSONObject fileJson = JSONUtil.readJSONObject(new File("data.json"), Charset.UTF_8); // 写入JSON文件 JSONUtil.writeJSON(new File("output.json"), jsonObj, Charset.UTF_8); ``` 5. **格式化输出** ```java String prettyJson = JSONUtil.toJsonPrettyStr(jsonStr); // 带缩进的美化格式 ``` --- #### 二、特殊场景处理 1. **忽略空值字段** ```java JSONConfig config = new JSONConfig().setIgnoreNullValue(true); String json = JSONUtil.toJsonStr(obj, config); ``` 2. **键名下划线转换** ```java // 对象字段userName转为user_name JSONConfig config = new JSONConfig().setKeyTransCase(KeyTransCase.UNDERSCORE); ``` 3. **XML互转** ```java String xml = JSONUtil.toXmlStr(jsonObj); // JSON转XML JSONObject xmlJson = JSONUtil.xmlToJson(xml); // XML转JSON ``` --- #### 三、引用说明 Hutool的$JSONUtil$通过链式调用和配置参数简化了复杂场景处理,其文件读写方法底层基于$IoUtil$实现高效流操作[^1]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值