gpt4 book ai didi

c# - 使用嵌入字符串中的大括号反序列化 JSON

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

这个 JSON 负载中的一个节点让我抓狂。

它的格式类似于字符串(在引号内),但它不会进入我的对象的字符串。

这是我收到的整个有效载荷:

{
"Event_Id":"da89afe72b41cb685f03261d8cb18d9e",
"Event_Name":"Employee Created",
"Event_DateTime":1655144130,
"ClientCode":"XXXXX",
"Resource_Field":"Employee",
"Resource_Identifier":null,
"Object":null,
"Object_Identifier":"9995",

"Data":"{"Employee_ID":"9995","Is_Rehire":"N","Was_New_Hire":"Y"}",

"Endpoint":"Employee",
"EndpointUrl":"api/v1/employee/9995"
}

问题是 “Data” 属性,为清楚起见将其分开。

这是它加载到的对象:

public class OutsideEvent
{
public string Event_Id { get; set; }
public string Event_Name { get; set; }
public int Event_DateTime { get; set; }
public string ClientCode { get; set; }
public string Resource_Field { get; set; }
public object Resource_Identifier { get; set; }
public object Object { get; set; }
public string? Object_Identifier { get; set; }

**public string? Data { get; set; }**

public string Endpoint { get; set; }
public string EndpointUrl { get; set; }
}

使用 Postman,我可以删除“Data”值周围的引号,将类型更改为对象并将其反序列化为:

public class eventData
{
public string Employee_ID { get; set; }
public string Is_Rehire { get; set; }
public string Was_New_Hire { get; set; }
}

但是我不能让发件人删除引号,所以我必须以某种方式处理它?<​​/p>

还尝试用 [JsonIgnore] 装饰 Data 属性,因为我不关心这个值,但它没有改变任何东西。

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

谢谢!

最佳答案

json 数据属性是无效字符串,因为它包含双引号中包含的双引号

....
"Data":"{"Employee_ID":"9995","Is_Rehire":"N","Was_New_Hire":"Y"}",
....

所以只需删除外部双引号,您可以使用字符串替换功能来完成

    json = json.Replace("\"{", "{").Replace("}\"","}");

现在你有了一个有效的 json

...
"Data":{"Employee_ID":"9995","Is_Rehire":"N","Was_New_Hire":"Y"},
....

你可以将它反序列化为c#

    Root root=JsonConvert.DeserializeObject<Root>(json);

public class Data
{
public string Employee_ID { get; set; }
public string Is_Rehire { get; set; }
public string Was_New_Hire { get; set; }
}

public class Root
{
public string Event_Id { get; set; }
public string Event_Name { get; set; }
public int Event_DateTime { get; set; }
public string ClientCode { get; set; }
public string Resource_Field { get; set; }
public object Resource_Identifier { get; set; }
public object Object { get; set; }
public string Object_Identifier { get; set; }
public Data Data { get; set; }
public string Endpoint { get; set; }
public string EndpointUrl { get; set; }
}

关于c# - 使用嵌入字符串中的大括号反序列化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72706197/

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