json挑战,带有领先或落后空间的会员名称

发布于 2025-01-31 13:08:58 字数 625 浏览 1 评论 0原文

如果JSON字符串具有带有领先/尾随的白色空间的成员名称,则可以将JSON字符串列为对象。我正在使用newtonsoft.json作为我的序列化库。

例如,以下是我的对象类型:

public class Sample
{
    public ComplexType Default {get; set;}
}
public class ComplexType
{
    public IEnumerable<string> Data {get; set;}
}

我想要的是,如果我的json字符串下方,则应该将其划分为有效的示例对象。请注意,下面的名称中有尾随的空格。使用[jsonproperty(propertyName =“ default”)的“默认”成员在类中不是一个选项,因为从理论上讲,我可以拥有任何数量的领先和/或尾随的空间。

{
    "Default   ":
    {
      "Data":["data1","data2"]
    }
}

请让我知道newtonsoft.json中是否有任何开箱即用支持或其他解决此问题的方法。我正在寻找一种通用解决方案,该解决方案可以适用于任何对象结构。

更新: 更新的对象结构和预期解决方案。

Is it possible to deserialize a Json string to an object if Json string has member names with leading/trailing white spaces. I am using Newtonsoft.Json as my serialization library.

For example following is my object type:

public class Sample
{
    public ComplexType Default {get; set;}
}
public class ComplexType
{
    public IEnumerable<string> Data {get; set;}
}

What I want is if I have below Json string then also it should be deserialized to a valid Sample object. Note there are trailing whitespaces in the name below. Decorating "Default" member with [JsonProperty(PropertyName = "Default ")] in the class is not an option because theoretically I can have any number of leading and/or trailing whitespaces.

{
    "Default   ":
    {
      "Data":["data1","data2"]
    }
}

Please let me know if there is any out of the box support in Newtonsoft.Json or other approach to solve this. I am looking for a generic solution which can work for any Object structure.

UPDATE:
Updated object structure and expected solution.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

埖埖迣鎅 2025-02-07 13:08:58

您不能仅仅更改jobignt属性名称,只能读取。您只能使用此代码创建一个新的JSON对象,例如

    var sampleObj=new JObject();

    var jsonParsed=JObject.Parse(json);
    foreach (var prop in jsonParsed.Properties())
        sampleObj.Add(prop.Name.Trim(),prop.Value);
    

   Sample sample=sampleObj.ToObject<Sample>();

如果您的对象非常复杂,则只需将代码添加到迭代儿童对象即可。或者,例如使用Regex来修复JSON字符串是有意义的。

You can't just change JObject property name, it is read only. You can only create a new json object using this code for example

    var sampleObj=new JObject();

    var jsonParsed=JObject.Parse(json);
    foreach (var prop in jsonParsed.Properties())
        sampleObj.Add(prop.Name.Trim(),prop.Value);
    

   Sample sample=sampleObj.ToObject<Sample>();

UPDATE

if your object is very complicated , you just have to add the code to iterate children objects. Or maybe it makes some sense to use RegEx for example to fix a json string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文