【问题标题】:How To Convert Json Array to String Array in C#如何在 C# 中将 Json 数组转换为字符串数组
【发布时间】:2018-06-02 08:09:02
【问题描述】:

我有一个 Json 输出如下

[
    {
        "eng_trans": "wide, outstretched,"
    },
    {
        "eng_trans": "width,breadth, town, street,earth, country, greatness."
    },
    {
        "eng_trans": "wife, the mistress of the house,"
    },
    {
        "eng_trans": "wide agricultural tract,"
    },
    {
        "eng_trans": "waste land the land which is not suitabie for cultivation."
    }] 

我只需要取出没有键的单词,并且需要在c#中形成一个字符串列表。有没有更好的方法来做到这一点。

【问题讨论】:

  • 到目前为止您尝试了哪些方法,哪些方法不适合您。例如,您是否尝试过使用模型类?
  • 或者不使用模型类,而只使用 LINQ to JSON - 将其解析为 JArray,然后从数组中的每个 JObject 中获取 eng_trans 值。
  • 你有newtonsoft json吗?

标签: c# json list


【解决方案1】:
public class RootObject
{
     public string eng_trans { get; set; }
}

这样就可以了。

  //list to store the words
 List<string> wordList = new List<string>();
 //Convert your json to string.I have already done it for you.
 string json = "[{      \"eng_trans\": \"wide, outstretched,\"  },  {       \"eng_trans\": \"width,breadth, town, street,earth, country, greatness.\"   },  {       \"eng_trans\": \"wife, the mistress of the house,\" },  {       \"eng_trans\": \"wide agricultural tract,\" },  {       \"eng_trans\": \"waste land the land which is not suitabie for cultivation.\"   }]";
 //Add Newtonsoft.Json from Nuget to do this deserialization.
 List<RootObject> eng_trans_List = Newtonsoft.Json.JsonConvert.DeserializeObject<List<RootObject>>(json);

  foreach(RootObject obj in eng_trans_List)
  {
      string[] str =  obj.eng_trans.Split(',');
      foreach(string word in str)
      {
         wordList.Add(word);
      }
  }

【讨论】:

    【解决方案2】:

    使用 Newtonsoft.json.dll。

    并将 Json 字符串转换为数组。

    检查此链接: https://www.newtonsoft.com/json https://www.codeproject.com/Questions/1074904/How-to-convert-Json-string-to-list-of-objects

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多