gpt4 book ai didi

C# JsonSerializer.Serialize 返回一个空对象

转载 作者:行者123 更新时间:2023-12-04 13:13:23 28 4
gpt4 key购买 nike

我遇到了将 struct 序列化为 JSON 的问题。所以,我有一个结构“坐标”

namespace CoordinatesNameSpace
{
public struct Coordinates
{
public Coordinates(string key, string x, string y, string z)
{
this.key = key;
this.x = x;
this.y = y;
this.z = z;
}
public string key;
public string x;
public string y;
public string z;
public override string ToString()
{
return $"{key} {this.x} {this.y} {this.z}";
}
}
}
所有属性都是公共(public)属性,所以我希望 json 序列化程序会返回我 { "key": "v", "x": "0.12331212"... },但它只返回一个空对象。
using CoordinatesNameSpace;

namespace ObjToJSON
{
class Program
{
static void Main(string[] args)
{
List<Coordinates> parsedCoordinatesList = new List<Coordinates>();
Coordinates _c;
_c.key = splitted[0]; // "v"
_c.x = splitted[1]; // "1.324394"
_c.y = splitted[2]; // "-0.219625"
_c.z = splitted[3]; // "-0.422554"
parsedCoordinatesList.Add(_c);

// returns an [{}, {}, {} ...]
//string json = JsonSerializer.Serialize<List<Coordinates>>(parsedCoordinatesList);

// returns {}
string json = JsonSerializer.Serialize<Coordinates>(parsedCoordinatesList[0]);
有人可以向我解释一下 - 为什么这样做以及如何使其正确序列化?

最佳答案

seems当前 System.Text.Json不支持序列化字段。将字段更改为属性,一切都应该正常工作:

public struct Coordinates
{
public Coordinates(string key, string x, string y, string z)
{
this.key = key;
this.x = x;
this.y = y;
this.z = z;
}
public string key { get; set; }
public string x { get; set; }
public string y { get; set; }
public string z { get; set; }
public override string ToString()
{
return $"{key} {this.x} {this.y} {this.z}";
}
}
同样来自 docs :

Serialization behavior:

...

  • Currently, fields are excluded.

关于C# JsonSerializer.Serialize 返回一个空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62717934/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com