各种数据形式转JSON与互转

引用

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

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);
}

Map转JSON

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);
}

List转JSON

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;
}

String转JSON

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

XML转JSON

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

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

油炸小波

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值