從多個方面詳細闡述JSON轉JSONObject

一、保持欄位順序

在JSON轉JSONObject過程中,很多情況下需要保證輸出的JSONObject中各欄位的順序與原來的JSON對象中保持一致,而不是按照默認的字典序排序。這種需求在解析某些數據時非常常見。下面是一個保持欄位順序的具體示例:

import com.alibaba.fastjson.JSONObject;

public class JsonConverter {
    public static JSONObject restoreOrder(JSONObject jsonObject) {
        Map map = new LinkedHashMap();  // 使用LinkedHashMap保證順序
        for (Map.Entry entry : jsonObject.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            if (value instanceof JSONObject) {
                value = restoreOrder((JSONObject) value);  // 遞歸解析JSONObject的子對象
            }

            map.put(key, value);
        }
        return new JSONObject(map);
    }
}

上述代碼通過遞歸解析JSONObject的子對象,並使用LinkedHashMap保存子對象條目的順序,最終按照原有順序輸出JSONObject對象。

二、JSON轉Excel

將JSON轉換為Excel表格是一種常見需求,這種轉換通常用於數據可視化,或者用於對數據進行分析和處理。Java中提供了多種Excel生成工具,比如POI、JExcelApi等。下面是一個使用POI進行JSON轉Excel的例子:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.FileOutputStream;
import java.util.Iterator;

public class JsonConverter {
    public static void convertToExcel(JSONObject jsonObject, String outputFilePath) throws Exception {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        // 添加表頭
        Row headerRow = sheet.createRow(0);
        Iterator keys = jsonObject.keySet().iterator();
        int i = 0;
        while (keys.hasNext()) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(keys.next());
            i++;
        }

        // 添加數據
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        for (int j = 0; j < jsonArray.size(); j++) {
            Row row = sheet.createRow(j + 1);  // 表頭佔用了第一行,所以從第二行開始添加數據
            JSONObject dataObject = jsonArray.getJSONObject(j);
            Iterator dataKeys = dataObject.keySet().iterator();
            int k = 0;
            while (dataKeys.hasNext()) {
                Cell cell = row.createCell(k);
                cell.setCellValue(dataObject.getString(dataKeys.next()));
                k++;
            }
        }

        // 輸出Excel文件
        FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath);
        workbook.write(fileOutputStream);
        fileOutputStream.close();
    }
}

上述代碼將JSONObject對象中的數據輸出到Excel文件中。

三、JSON轉Protobuf

Protobuf是Google開發的一種二進位序列化協議,可以簡化數據的序列化和反序列化過程,同時提供了更好的性能和更小的數據傳輸體積。下面是一個示例,展示如何將JSON對象轉換為Protobuf格式:

syntax = "proto3";

message Person {
    string name = 1;
    int32 age = 2;
}

message PersonList {
    repeated Person items = 1;
}

import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

public class JsonConverter {
    public static PersonList convertToProtobuf(JSONObject jsonObject) {
        PersonList.Builder builder = PersonList.newBuilder();
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject dataObject = jsonArray.getJSONObject(i);
            Person.Builder personBuilder = Person.newBuilder();
            personBuilder.setName(dataObject.getString("name"));
            personBuilder.setAge(dataObject.getInteger("age"));
            builder.addItems(personBuilder.build());
        }
        return builder.build();
    }

    public static JSONObject convertFromProtobuf(PersonList personList) throws InvalidProtocolBufferException {
        JSONObject result = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        List personListItems = personList.getItemsList();
        for (Person person : personListItems) {
            JSONObject personObject = new JSONObject();
            personObject.put("name", person.getName());
            personObject.put("age", person.getAge());
            jsonArray.add(personObject);
        }
        result.put("data", jsonArray);
        return result;
    }

    public static ByteString serialize(PersonList personList) {
        return personList.toByteString();
    }

    public static PersonList deserialize(ByteString bytes) throws InvalidProtocolBufferException {
        return PersonList.parseFrom(bytes);
    }
}

上述代碼定義了一個Protobuf的數據結構,用於存儲Person對象。其中,PersonList對象包含了多個Person對象,且Person對象的關鍵欄位包括name和age。convertToProtobuf方法將JSONObject對象轉換為PersonList對象,而convertFromProtobuf方法則是將PersonList對象反序列化為JSONObject對象。serialize和deserialize方法分別將PersonList對象序列化為二進位格式和反序列化為PersonList對象。

四、JSON轉XML

XML是另一種常見的數據交換格式,而Java也提供了多種將Java對象轉換為XML格式的工具庫,比如JAXB、XStream等。下面是一個使用JAXB進行JSON轉XML的示例:

import com.alibaba.fastjson.JSONObject;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;

public class JsonConverter {
    public static String convertToXml(JSONObject jsonObject) throws JAXBException {
        // 創建JAXBContext對象,用於轉換Java對象到XML文件
        JAXBContext jaxbContext = JAXBContext.newInstance(Container.class);
        Marshaller marshaller = jaxbContext.createMarshaller();

        // 設置marshaller,保證生成的XML文件具有良好的可讀性
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        Container container = new Container();
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject dataObject = jsonArray.getJSONObject(i);
            Data data = new Data();
            data.setName(dataObject.getString("name"));
            data.setAge(dataObject.getInteger("age"));
            container.getData().add(data);
        }

        StringWriter stringWriter = new StringWriter();
        marshaller.marshal(container, stringWriter);
        return stringWriter.toString();
    }
}

@XmlRootElement
class Container {
    private List data = new ArrayList();

    @XmlElement(name = "data")
    public List getData() {
        return data;
    }
}

class Data {
    private String name;
    private Integer age;

    @XmlElement
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlElement
    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

上述代碼創建了Container和Data兩個POJO,在convertToXml方法中,將JSONObject對象按照XML數據結構填充到Container對象中,並使用JAXBContext和Marshaller將Container對象轉換為XML字元串。

五、jQuery轉JSON

jQuery是一個流行的JavaScript庫,它提供了豐富和易於使用的API,用於簡化HTML文檔的遍歷和操作。在頁面中引入jQuery之後,可以通過下述方式獲取JSON對象:

var jsonObject = $.parseJSON(str);  // str是一個JSON格式字元串

上述代碼中,$.parseJSON方法將JSON格式字元串轉換為JSONObject對象。

六、JSON轉String

將JSON對象轉換為字元串通常用於將JSON數據上傳到伺服器端或者輸出到客戶端。Java的fastjson庫提供了多個將JSON對象轉換為字元串的API,比如toJSONString、toJSON等。下面是一個toJSONString的例子:

import com.alibaba.fastjson.JSONObject;

public class JsonConverter {
    public static String convertToString(JSONObject jsonObject) {
        return jsonObject.toJSONString();
    }
}

上述代碼使用toJSONString方法將JSONObject對象轉換為字元串。

七、JSON轉換

除了JSON轉換成JSONObject、XML等格式之外,還可以對JSON數據進行一些轉換操作。Java的fastjson庫提供了多個JSON轉換方法,比如toJavaObject、toJSONString、toJSON等。下面是一個toJavaObject的例子:

import com.alibaba.fastjson.JSONObject;

public class JsonConverter {
    public static Person convertToJavaObject(JSONObject jsonObject) {
        return jsonObject.toJavaObject(Person.class);
    }
}

class Person {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

上述代碼中,使用fastjson的toJavaObject方法將JSONObject轉換為Java對象Person。

八、JSON串轉Map

將JSON格式的字元串轉換為Java的Map類型也是一種常見需求,Java的fastjson庫同樣提供了相關API。下面是一個示例代碼:

import com.alibaba.fastjson.JSON;
import java.util.Map;

public class JsonConverter {
    public static Map convertToMap(String jsonString) {
        return JSON.parseObject(jsonString, new TypeReference<Map>(){});
    }
}

上述代碼中,通過JSON.parseObject將JSON格式的字元串轉換為Map類型。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/182099.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-11-24 06:18
下一篇 2024-11-24 06:18

相關推薦

發表回復

登錄後才能評論