JSONUtil

简介: 111

引用

以下包在未主动声明前提下,均为下述引用

import cn.hutool.core.util.XmlUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.List;
import java.util.Map;

一维数组转JSON

public static String arrToJson(String[] arr) {
    String jsonStr = JSONArray.fromObject(arr).toString();
    System.out.println("数组转json:" + jsonStr);
    return jsonStr;
}

二维数组转JSON

public static String twoArrToJson(String[][] arr) {
    String jsonStr = JSONArray.fromObject(arr).toString();
    System.out.println("数组转json:" + jsonStr);
    return jsonStr;
}

Object转JSON

public static String objectToJson(Object object) {
    String jsonStr = JSONArray.fromObject(object).toString();
    System.out.println("对象转json:" + jsonStr);
    return jsonStr;
}

JSON转Object

public static <T> T jsonToObject(String pojo, Class<T> clazz) {
    return com.alibaba.fastjson.JSONObject.parseObject(pojo, clazz);
}

MapJSON

public static String mapToJson(Map<String, Object> map) {
    String jsonStr = JSONObject.fromObject(map).toString();
    System.out.println("map转json:" + jsonStr);
    return jsonStr;
}

JSON转Map

public static void jsonToMap(String jsonStr) {
    Map<String, Object> map= (Map<String, Object>)com.alibaba.fastjson.JSONObject.parse(jsonStr);
}

ListJSON

public static String listToJson(List<?> list) {
    String jsonStr = JSONArray.fromObject(list).toString();
    System.out.println("list转json:" + jsonStr);
    return jsonStr;
}

JSON转List

public static <T> List<T> jsonToList(String jsonString, Class<T> clazz) {
    List<T> ts = com.alibaba.fastjson.JSONArray.parseArray(jsonString, clazz);
    return ts;
}

StringJSON

public static void stringToJson(String[] args) {
    String str = "{\"result\":\"success\",\"message\":\"成功!\"}";
    JSONObject json = JSONObject.fromObject(str);
    System.out.println(json.toString());
}

XMLJSON

public static JSONObject xmlToJson(String xmlStr) {
    Map<String, Object> result = XmlUtil.xmlToMap(xmlStr);
    JSONObject jsonObject = JSONObject.fromObject(result);
    System.out.println(jsonObject);
    return jsonObject;
}


相关文章
|
3月前
|
SQL 监控 机器人
|
3月前
|
安全 数据安全/隐私保护
|
3月前
|
前端开发 数据安全/隐私保护
|
3月前
|
Java 开发工具 Maven
|
3月前
|
安全 Java 数据安全/隐私保护
|
3月前
|
存储 缓存 Java
|
3月前
|
自然语言处理 fastjson Java
|
3月前
|
运维 Devops 开发工具
|
3月前
|
Java 测试技术 Linux

热门文章

最新文章