gpt4 book ai didi

c# - 无法以字符串格式从 JSON 重新创建 JSON 值

转载 作者:行者123 更新时间:2023-11-30 17:05:16 24 4
gpt4 key购买 nike

我有以下对象:

public class TestModel
{
public object TestValue { get; set; }
}

我的数据库包含 JSON 格式的字符串,例如

string dbValue1 = "[\"test value\"]"
string dbValue2 = "[\"one value\",[\"another value|or this value\"]]"
int dbValue3 = 1
bool dbValue4 = true

我需要将这些值反序列化为 TestModel.TestValue 属性,这样当我序列化对象时,我得到的格式与存储在数据库中的格式相同。我显然可以得到一个 intbool 一个基本数组来工作,但我不能在稍微复杂的数组的情况下。从上面的 dbValue2 我希望输出是:

"testValue" : ["one value",["another value|or this value"]]

现在,我正在使用 ServiceStack.Text,到目前为止,这是我尝试过的:

TestValue = JsonSerializer.DeserializeFromString(dbValue, typeof(object))
TestValue = dbValue.FromJson<object>()
TestValue = JsonObject.Parse(dbValue)

这些生成:

"testValue":"[one value,[another value|or this value]]"
"testValue":{"one value":["another value|or this value"]}
"testValue":{"one value":["another value|or this value"]}

我能理解为什么这些不起作用,但我不知道如何做我需要的。

如有任何帮助,我们将不胜感激。

最佳答案

因为根元素是JSON中的一个数组。 ServiceStack 似乎对此感到窒息。

如果你尝试使用 ServiceStack 并添加一个与属性相同的数组的根对象,例如

var json = "{\"root\":[\"one value\",[\"another value|or this value\"]]}";
var testValue = JsonObject.Parse(json);
Console.WriteLine(testValue.ToJson());

它正确地序列化了数组。

Json.Net似乎只是工作。

var json = "[\"one value\",[\"another value|or this value\"]]";            
var testValue = JsonConvert.DeserializeObject(
Console.WriteLine(JsonConvert.SerializeObject(testValue));

烦人:)

关于c# - 无法以字符串格式从 JSON 重新创建 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16716725/

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