使用"0"将JSON解析为C#对象.作为JSON字符串中的对象名称 [英] Parse JSON into C# object with "0" as object name inside JSON string

查看:151
本文介绍了使用"0"将JSON解析为C#对象.作为JSON字符串中的对象名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到使用MVC4启动Web会话的JSON对象.我需要将其解析为C#对象以供以后使用.我无法更改收到的对象-它来自第三方.

I receive a JSON obejct to start a web session, using MVC4. I need to parse it into a C# object for later use. I cannot change the object I receive - it comes from a third party.

我用来解析的方法:

MyClass jsonObject = new MyClass();

//The 2 lines below will not work with the given answer
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//jsonObject = serializer.Deserialize<MyClass >(jsonString);

//Use this method instead
jsonObject = JsonConvert.DeserializeObject<MyClass>(jsonString);

问题: 由于内部对象的名称为"0",我无法为JSON的这一部分定义C#类.

QUESTION: I'm having trouble defining the C# class for this part of the JSON due to the "0" name of internal object.

JSON:

{
    "header": {
        "to": {
            "data": [],
            "0": {
                "data": [],
                "value": "1101",
                "domain": "DUNS"
            }
        },
        "from": {
            "data": [],
            "0": {
                "data": [],
                "value": "1101",
                "domain": "NetworkID"
            }
        },
        "sender": {
            "data": {
                "UserAgent": "Test Client v1"
            },
            "0": {
                "data": {
                    "SharedSecret": "test"
                },
                "value": "testing@smith.com",
                "domain": "testClientID"
            }
        }
    },
...
}

注意::我尝试了在线json到C#类生成器,要么失败,要么创建名称为'0'的类,而该类当然不会编译.

NOTE: I have tried online json to C# class generators, either failure, or creating a class with a name '0' which of course does not compile.

评论: MyClass将是这样的:

Comments: MyClass would be something like this:

public class Header
{
    public ToClass to = new ToClass ();
    public FromClass to = new FromClass ();
}

public class ToClass 
{
    public Data[];
    public zero 0 = new zero();
}

public class zero
{
    public string data { get; set; }
    public string value { get; set; }
    public string domain { get; set; }
}

推荐答案

我相信您可以使用json.NET的property属性系统来更正此问题,文档位于此处. http://james.newtonking.com/json/help /index.html?topic=html/SerializationAttributes.htm

I believe you can use json.NET's property attribute system to correct this, the docs are here. http://james.newtonking.com/json/help/index.html?topic=html/SerializationAttributes.htm

public class ToClass 
{
    public Data[];
    [JsonProperty(PropertyName = "0")]
    public zero Zero = new zero();
}

这将使反序列化器将名为0的json属性与名为Zero

This will make it so the deserializer equates the json property named 0 with the C# property named Zero

这篇关于使用"0"将JSON解析为C#对象.作为JSON字符串中的对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆