名称带有括号和括号时反序列化JSON [英] Deserialize JSON When Names Have Brackets and Parentheses

查看:178
本文介绍了名称带有括号和括号时反序列化JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用第三方提供的JSON,如下所示:

I am consuming JSON from a third party that looks like this:

 {"id":"1","[question(21), option(\"10033-other\")]":"","[question(22)]":"electric"}

我了解当键名是简单字符串时如何获取值.但是,当键名不是基本字符串时,我无法弄清楚如何获取值.我将如何反序列化[question(21)]和[question(22)]值?

I understand how to get the values out when the key name is a simple string. But I cannot figure out how to get the values out when the key name is not a basic string. How would I deserialize the [question(21)] and [question(22)] values?

我的代码在下面.

课程:

public class MyFeed
{
    public string id { get; set; }
}

public class MyFeedClass
{
    public List<MyFeed> data { get; set; }
}

Program.cs

Program.cs

    static void Main(string[] args)
    {
        string webReq = String.Empty;
        webReq += "https://restapi.surveygizmo.com/head/survey/zzzzzzzzz";
        webReq += "/surveyresponse/";
        webReq += "?user:pass=xxxxxx:yyyyyyyyy";
        HttpWebRequest request = WebRequest.Create(webReq) as HttpWebRequest;
        var myString = String.Empty;
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            myString += reader.ReadToEnd();
        }        

        MyFeedClass myFeedClass = 
            new JavaScriptSerializer().
            Deserialize<MyFeedClass>(myString);

        Console.Title = "Bentley - Survey Data Loader";
        Console.WriteLine("");
        foreach (var item in myFeedClass.data)
        {
            Console.WriteLine("id: {0}", item.id);
        }
        Console.WriteLine("");
        Console.WriteLine("Press enter to exit...");
        Console.ReadLine();
    }

推荐答案

您的JSON和您的类看起来不匹配-也就是说,通过一些调整,您可以得到一些东西反序列化:

Your JSON and your classes don't look like they match up - that said, with a bit of tweaking, you can get something to deserialize out of it:

如果我们像这样包装您发布的JSON:

If we wrap the JSON you posted like so:

string data =  @"{""data"":{""id"":""1"",""[question(21), option(\""10033-other\"")]"":"""",""[question(22)]"":""electric""}}";

(或非损坏形式)

{"data":{"id":"1","[question(21), option(\"10033-other\")]":"","[question(22)]":"electric"}}

然后重新定义提要类:

public class MyFeedClass
{
    public Dictionary<string,string> data { get; set; }
}

new JavaScriptSerializer().Deserialize<MyFeedClass>(data)

产生包含内容的Dictionary<string,string>

{id, 1 }
{[question(21), option("10033-other")], }
{[question(22)], electric }

这篇关于名称带有括号和括号时反序列化JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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