简体   繁体   中英

How to trim and extract JSON string via C# RegEx?

I have a json string that I will like to grab only the array in the data node. Do I trim using RegEx or what is the best way to extract that portion of the json string?

Here is a sample:

{
   "Data":[
      {
         "Title":"Test Item 1",
         "Icon":"pdf",
         "PublicationDate":"2013-05-08T18:23:18.037Z"
      },
      {
         "Title":"Test Item 2",
         "Icon":"pdf",
         "PublicationDate":"2013-05-08T18:23:38.177Z"
      }
   ],
   "Count":67
}

Below is what I want to end up with:

   [
      {
         "Title":"Test Item 1",
         "Icon":"pdf",
         "PublicationDate":"2013-05-08T18:23:18.037Z"
      },
      {
         "Title":"Test Item 2",
         "Icon":"pdf",
         "PublicationDate":"2013-05-08T18:23:38.177Z"
      }
   ]

How can I do this properly? Sometimes the json string already comes as I need with only the array in the data node, so the logic has to be smart enough to ignore it if it already comes in that format. The reason is because I am feeding both cases to JsonConvert.DeserializeObject<List<dynamic>>(json) . Thanks for any help!

After reading your comments, it seems that this is what you need:

var jToken=JToken.Parse(data);
JArray arr;
switch(jToken.Type)
{
    case JTokenType.Array:
        arr=(JArray)jToken;
        break;
    case JTokenType.Object:
        arr=(JArray)((JObject)jToken)["Data"];
        break;
    default:
        throw new Exception();
}
var output=arr.ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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