如何使用C#

时间:2018-01-11 06:05:25

标签: c# json

我有像JSON一样的

string fields = "{'foo':'{\'Resources\':{\'resourceUri\':\'/xf/b/rs/RA-a-675e/fo/age/s/m78\',\'location\':\'us\',\'tags\':{\'displayName\':\'A's storage\',\'container.registry\':\'dd\'}}}'}";

不幸的是,我无法更改JSON以上

var customDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(fields);

始终抛出异常。为什么呢?

3 个答案:

答案 0 :(得分:2)

这个JSON不仅仅是一个简单的Dictionary<string, string>!它是一种自定义类型,如下所示:

JSON:

{foo:{Resources:{resourceUri:"/xf/b/rs/RA-a-675e/fo/age/s/m78",location:"us",tags:{displayName:"As storage",containerregistry:"dd"}}}}

C#类:

public class Tags
{
    public string displayName { get; set; }
    public string containerregistry { get; set; }
}

public class Resources
{
    public string resourceUri { get; set; }
    public string location { get; set; }
    public Tags tags { get; set; }
}

public class Foo
{
    public Resources Resources { get; set; }
}

public class Example
{
    public Foo foo { get; set; }
}

之后你可以反序列化:

var customObject = JsonConvert.DeserializeObject<Foo>(fields);

答案 1 :(得分:0)

如果要将此JSON字符串解析为Dictionary<string, string>,则可以将每个\替换为\\,并将A's storage替换为A\\'s storage。替换后,输入字符串变为如下:

string fields = "{'foo':'{\\'Resources\\':{\\'resourceUri\\':\\'/xf/b/rs/RA-a-675e/fo/age/s/m78\\',\\'location\\':\\'us\\',\\'tags\\':{\\'displayName\\':\\'A\\'s storage\\',\\'container.registry\\':\\'dd\\'}}}'}";

然后当你打电话:

var customDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(fields);

customDict只包含一个键值对:

customDict["foo"] == "{'Resources':{'resourceUri':'/xf/b/rs/RA-a-675e/fo/age/s/m78','location':'us','tags':{'displayName':'A's storage','container.registry':'dd'}}}"

答案 2 :(得分:0)

我不知道为什么你的json字符串出了问题。无论如何,我认为这是你固定的json字符串

IWebElement

为您的项目安装string jsonString = "{'foo':{'Resources':{'resourceUri':'/xf/b/rs/RA-a-675e/fo/age/s/m78','location':'us','tags':{'displayName':'As storage','containerregistry':'dd'}}}}"; Manage Nuget Packages,然后将这些Newtonsoft.Json类用于您的json字符串

POCO

现在您可以将json字符串反序列化为C#对象

public class Rootobject
{
    public Foo foo { get; set; }
}

public class Foo
{
    public Resources Resources { get; set; }
}

public class Resources
{
    public string resourceUri { get; set; }
    public string location { get; set; }
    public Tags tags { get; set; }
}

public class Tags
{
    public string displayName { get; set; }
    public string containerregistry { get; set; }
}

这是一个完整的控制台应用程序示例

var deserializedRootObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(jsonString);

System.Console.WriteLine(deserializedRootObject.foo.Resources.location); // us