常见编程语言的json序列化与序列化代码片段(java/python/js/c#/ruby/c++)

json序列化与反序列化

Python

import json

# 序列化为 JSON
data = {"name": "John", "age": 30}
serialized_data = json.dumps(data)

# 反序列化 JSON
deserialized_data = json.loads(serialized_data)

Java

import java.io.*;
import com.google.gson.Gson;

// 序列化为 JSON
class Data implements Serializable {
    public String name;
    public int age;
}

Data data = new Data();
data.name = "John";
data.age = 30;

Gson gson = new Gson();
String serialized_data = gson.toJson(data);

// 反序列化 JSON
Data deserialized_data = gson.fromJson(serialized_data, Data.class);

JavaScript

// 序列化为 JSON
var data = {name: "John", age: 30};
var serialized_data = JSON.stringify(data);

// 反序列化 JSON
var deserialized_data = JSON.parse(serialized_data);

json 格式化

特意提一下js中格式化也特别方便

const jsonString = '{"name":"John","age":30,"city":"New York"}';
// 格式化JSON字符串
const formattedJsonString = JSON.stringify(JSON.parse(jsonString), null, 2);
console.log(formattedJsonString);

这是我写的一个json格式化小工具,核心代码就只有上面三行

C#

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json;

// 序列化为二进制
class Data {
    public string name;
    public int age;
}

Data data = new Data();
data.name = "John";
data.age = 30;

BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, data);
byte[] serialized_data = stream.ToArray();

// 反序列化二进制
stream = new MemoryStream(serialized_data);
Data deserialized_data = (Data)formatter.Deserialize(stream);

ruby

require 'json'

# 序列化为 JSON
data = { "name" => "John", "age" => 30 }
serialized_data = data.to_json

# 反序列化 JSON
deserialized_data = JSON.parse(serialized_data)

C++

#include <iostream>
#include <string>
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"

using namespace rapidjson;

struct Data {
    std::string name;
    int age;
};

// 序列化为 JSON
Data data;
data.name = "John";
data.age = 30;

Document document;
document.SetObject();
Value name(data.name.c_str(), document.GetAllocator());
Value age(data.age);
document.AddMember("name", name, document.GetAllocator());
document.AddMember("age", age, document.GetAllocator());

StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
document.Accept(writer);

std::string serialized_data = buffer.GetString();

// 反序列化 JSON
Document deserialized_data;
deserialized_data.Parse(serialized_data.c_str());

Data result;
result.name = deserialized_data["name"].GetString();
result.age = deserialized_data["age"].GetInt();

posted @ 2023-11-01 16:26  xdzhcs  阅读(26)  评论(0编辑  收藏  举报