简体   繁体   English

元组如何序列化为 JSON 和反序列化 JSON?

[英]How does a Tuple serialize to and deserialize from JSON?

I am curious about how the Tuple<T1, T2, T3, ...> serializes and deserializes.我很好奇Tuple<T1, T2, T3, ...>序列化和反序列化。 I searched using keywords "json" and "tuple" but I could not find what I want.我使用关键字“json”和“tuple”进行搜索,但找不到我想要的。

I test by UnitTest and Json.net , and the test codes is as following.我通过UnitTestJson.net进行测试,测试代码如下。 The results shows Tuple<T1,T2,T3,...> is serializable and deserializable.结果显示Tuple<T1,T2,T3,...>是可序列化和可反序列化的。 So I can use them in my application.所以我可以在我的应用程序中使用它们。

Test codes测试代码

public class Foo {
    public List<Tuple<string, string, bool>> Items { get; set; }

    public Foo()
    {
        Items = new List<Tuple<string, string, bool>>();
    }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        foreach (var a in Items)
        {
            sb.Append(a.Item1 + ", " + a.Item2 + ", " + a.Item3.ToString() + "\r\n");
        }
        return sb.ToString();
    }
}

[TestClass]
public class NormalTests
{
    [TestMethod]
    public void TupleSerialization()
    {
        Foo tests = new Foo();
        
        tests.Items.Add(Tuple.Create("one", "hehe", true));
        tests.Items.Add(Tuple.Create("two", "hoho", false));
        tests.Items.Add(Tuple.Create("three", "ohoh", true));

        string json = JsonConvert.SerializeObject(tests);
        Console.WriteLine(json);

        var obj = JsonConvert.DeserializeObject<Foo>(json);
        string objStr = obj.ToString();
        Console.WriteLine(objStr);
    }
}

Summary概括

  • Tuple.Create("own","hehe",true) serializes to {"Item1":"one","Item2":"hehe","Item3":true} Tuple.Create("own","hehe",true)序列化为{"Item1":"one","Item2":"hehe","Item3":true}

  • {"Item1":"one","Item2":"hehe","Item3":true} can be deserialized back to Tuple<string,string, bool> {"Item1":"one","Item2":"hehe","Item3":true}可以反序列化回Tuple<string,string, bool>

  • Class Foo with Tuple data, can be serialized to json string, and the string can be deserialized back to Class Foo .带有Tuple数据的Class Foo ,可以序列化为 json 字符串,字符串可以反序列化回Class Foo

If you are looking for a short answer.如果您正在寻找简短的答案。 I am using JsonConvert .我正在使用JsonConvert

var testTuple = Tuple.Create(1234, "foo", true);
var serialized = JsonConvert.SerializeObject(testTuple);

Console.WriteLine(serialized);
// prints: {"Item1":1234,"Item2":"foo","Item3":true}

I made a minimal fiddle .我做了一个最小的小提琴

Thank you Hinrich to the dotnetfiddle link above.感谢 Hinrich 到上面的 dotnetfiddle 链接。

i used the same link, and got to know how Conversion works between Json objects and Tuples.我使用了相同的链接,并了解了 Json 对象和元组之间的转换是如何工作的。 Below is the code :下面是代码:

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class Program
{
    public static void Main()
    {

        var testTuple = Tuple.Create<int, string, bool>(1234, "foo", true);
        var serialized = JsonConvert.SerializeObject(testTuple);
        Console.WriteLine(serialized);
        JObject test = ((JObject)JsonConvert.DeserializeObject(serialized));
        string strSerialized = JsonConvert.SerializeObject(test);
        //Tuple<int, string, bool> testTuple1 = JsonConvert.DeserializeObject<Tuple<int, string, bool>>(serialized); // WORKs
        Tuple<int, string, bool> testTuple1 = JsonConvert.DeserializeObject<Tuple<int, string, bool>>(strSerialized); // WORKs
        Console.WriteLine(testTuple1.Item1.ToString());
    }
}

Hope someone finds this helpful.希望有人觉得这有帮助。

With .NET5 and soon .NET6 it's now recommended to use System.Text.Json over NewtonSoft.对于 .NET5 和很快的 .NET6,现在建议使用System.Text.Json不是 NewtonSoft。 The important thing for this serializer with regard to tuples is to set the JsonSerializerOptions option IncludeFields , as otherwise tuple values are excluded by default.这个序列化器关于元组的重要事情是设置JsonSerializerOptions选项IncludeFields ,否则默认情况下排除元组值。

Below is a minimal example.下面是一个最小的例子。 (can paste into .NET fiddle with the .NET5 compiler) (可以使用 .NET5 编译器粘贴到.NET 中


using System;
using System.Collections.Generic;
using System.Text.Json;
                    
public class Program
{
    public static void Main()
    {
        JsonSerializerOptions options = new() { IncludeFields = true };

        var testTuple = ("test" , "test1", 1324, false);
        var serializedTuple = JsonSerializer.Serialize(testTuple, options);
        Console.WriteLine(serializedTuple)
    }
}

output:输出:

{"Item1":"test","Item2":"test1","Item3":1324,"Item4":false}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# 如何从产量 function 序列化/反序列化 IEnumerator(到 Json?) - C# How to Serialize/Deserialize an IEnumerator from a Yield function (to Json?) 如何使用.Text var序列化和反序列化Json - How to Serialize and Deserialize Json with a .Text var 如何正确序列化和反序列化 Json 中的对象列表? - How correctly serialize and deserialize List of objects in Json? 如何将json字典序列化/反序列化为数组 - How to serialize/deserialize json dictionary into array 如何序列化和反序列化复杂的嵌套 json Unity? - How to serialize and deserialize complex nested json Unity? 将元组序列化为JSON - Serialize tuple to JSON 如何从一种类型序列化/反序列化到另一种类型? - How to serialize/deserialize from one type to another? 如何将 JSON 上的属性从一种类型反序列化,但序列化为具有相同名称的另一种类型? - How to deserialize a property on JSON from one type but serialize to another type with the same name? 从同一JSON属性从不同的对象属性进行序列化和反序列化 - Serialize from and deserialize into different object property from same JSON property 由 Newtonsoft.Json.JsonConvert 从同一个类序列化 nad 反序列化 - Serialize nad Deserialize from this same Class by Newtonsoft.Json.JsonConvert
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM