简体   繁体   English

C#-从JSON到键值,反之亦然

[英]C# - JSON to Key Value & vice versa

I am fetching a string from a JSON file & want to convert it to Key-Value pair. 我正在从JSON文件中提取字符串,并希望将其转换为键值对。

I am using JSON.NET for the same. 我使用JSON.NET相同。

I know I can deserialize a List using: 我知道我可以使用以下方法反序列化列表:

List<JsonClass> jsonFileComments = JsonConvert.DeserializeObject<List<JsonClass>>(json);

And I can Deserialize a Array using: 我可以使用以下方法反序列化数组:

Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

But as my JSON string contains Lists & Arrays in single file only. 但是由于我的JSON字符串仅在单个文件中包含列表和数组。 The sequence is like: 顺序如下:

{
    List,
    List,
    List,
    Array,
    List, 
    Array,
    List 
}

Can you tell me how can I deserialize it using single way. 您能告诉我如何使用单一方法反序列化它吗?

Other way is I need to separate out the Arrays & work on separately. 另一种方法是我需要分离出阵列并单独进行工作。 And again while Serializing I need to work that stuff. 再次,在序列化时,我需要处理这些东西。

Well one way would be to use dynamic (The type is a static type, but an object of type dynamic bypasses static type checking.)? 一种方法是使用动态方法 (类型是静态类型,但是动态类型的对象绕过静态类型检查。)?

dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");

Console.WriteLine(d.number);
Console.WriteLine(d.str);
Console.WriteLine(d.array.Count);

Hope this code block helps. 希望此代码块对您有所帮助。 I'm assuming you have jSon object & you need to parse through it: 我假设您有jSon对象,并且需要通过它进行解析:

Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(yourJsonData);
Newtonsoft.Json.Linq.JArray textArray = (Newtonsoft.Json.Linq.JArray)o["yourArray"];
if (textArray.Count > 0)
{
for (int i = 0; i < textArray.Count; i++)
{//do something}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM