Home > Enterprise >  Get JSON element as string
Get JSON element as string

Time:01-06

I want the JSON array element to be converted as a string.

The JSON looks like this:

[{"id":373313181,"from":"[email protected]","subject":"example subject 123","date":"2022-01-06 13:22:14"}]

I want to get the ID element as a string.

I tried to do like that:

var json = "[{\"id\":373313181,\"from\":\"[email protected]\",\"subject\":\"example subject 123\",\"date\":\"2022-01-06 13:22:14\"}]";
var parse = JObject.Parse(json);
var id = parse["id"].ToString();
Console.WriteLine(id);

So that the output will be like this:

373313181

But that simply just didn't work. Any ideas why?

CodePudding user response:

Parse as JArray and take the first element of the array.

var json = "[{\"id\":373313181,\"from\":\"[email protected]\",\"subject\":\"example subject 123\",\"date\":\"2022-01-06 13:22:14\"}]";
var array = JArray.Parse(json);
var id = (string)array[0]["id"];

And from your question, cast the id to string as below:

var id = (string)array[0]["id"];

OR

var id = array[0]["id"].Value<string>();

Sample Program

CodePudding user response:

My implementation:

using System;
using Newtonsoft.Json;
        
public class Program
{
    public static void Main()
    {
        var json = "[{\"id\":373313181,\"from\":\"[email protected]\",\"subject\":\"example subject 123\",\"date\":\"2022-01-06 13:22:14\"}]";
        dynamic test = JsonConvert.DeserializeObject(json);
        Console.WriteLine(Convert.ToString(test[0].id));
        Console.WriteLine(Convert.ToString(test[0].id).GetType());

    }
}

//Output
373313181
System.String
  •  Tags:  
  • Related