简体   繁体   English

如何使用 C# 将 JSON 文件的文本拆分成片段

[英]how to split text of a JSON file into pieces using C#

I am having a JSON file like this:我有一个像这样的 JSON 文件:

[
    {
        Object0
        ...
    },
    {
        Object1
        ...
    },
    ...
    {
        Objectn
        ...
    }
]

How to split the text into peices of { Object } string?如何将文本拆分为 { Object } 字符串的片段? I mean a collection of string, such as string[] or List, espected output is for each of string there is something like this:我的意思是字符串的集合,例如字符串 [] 或列表,预计 output 对于每个字符串都有如下内容:

{
    text
}

So for just convert JSON String to array string, you need to split the string with this code:因此,只需将 JSON 字符串转换为数组字符串,您需要使用以下代码拆分字符串:

string jsonString= "{your json string}";
string[] MyObjects = jsonString.Split(',');

You can also parse it with JSON Parsers like NewtonJson or the default one!您还可以使用 JSON 解析器(如 NewtonJson 或默认解析器)对其进行解析!

var MyObjects = JsonConvert.DeserializeObject <Any type you want> (jsonData); 

OR Using JObject:或使用 JObject:

var MyObjects = JObject.Parse(jsonData); 

Or Use Default one:或使用默认值:

var MyObjects = (any type you want)serializer.DeserializeObject(jsonData);

JsonUtility is a solution if you use Unity (otherwise you might find classes mentioned by Ali Kianoor useful).如果您使用 Unity,JsonUtility 是一个解决方案(否则您可能会发现 Ali Kiano 提到的类很有用)。 This could be a suitable data structure:这可能是一个合适的数据结构:

[Serializable]
class A
{
    public string name;
}

[Serializable]
class B {
    public List<A> list;
}

As your jsonRawText is not in the format of a standard json, let's just trim it as jsonText:由于您的 jsonRawText 不是标准 json 的格式,因此我们将其修剪为 jsonText:

var jsonRawText = @"
    {
        ""name"": ""test 1"",
        ""value"": 123
    },
    {
        ""name"": ""test 2"",
        ""value"": 321
    }
";
var jsonText = "{\"list\": [" + jsonRawText + "]}";
var b = JsonUtility.FromJson<B>(jsonText);

And then copy strings in a list (if you wish):然后复制列表中的字符串(如果您愿意):

var list = new List<string>();
foreach (var item in b.list)
    list.Add(item.name);

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

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