简体   繁体   中英

Convert simple json to string array in c#

I am new to C# REST API... I am just converting JSON to a string array

Here is my JSON

[{"Id":1000,"Name":"May","Address":"Atlanda","Country":"USA","Phone":12345}}

convert array like below code

string[] details={1000,May,Atlanda,USA,12345};

Help me to solve this problem

My code

 public class details
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Address { get; set; }
            public string Country { get; set; }
            public int Phone { get; set; }
      }

This my class

          var client = new RestClient("http://localhost:3000/customer/1000");
            var request = new RestRequest(Method.GET);
            IRestResponse response = client.Execute(request);
            string json = new JavaScriptSerializer().Serialize(response.Content);

You can deserialize response.Content to details class as shown below using the new System.Text.Json APIs

JsonSerializer.Parse<details>(response.Content);

For further information you can read Try the new System.Text.Json APIs .

If you use JSON.NET, it will certainly make things easier for you. My answer uses JSON.NET:

string str = "[{\"Id\":1000,\"Name\":\"May\",\"Address\":\"Atlanda\",\"Country\":\"USA\",\"Phone\":12345}]";

var listOfDetails = JsonConvert.DeserializeObject<List<details>>(str);
foreach (var detail in listOfDetails)
{
    var arr = detail.ToArr();
}

Following is the details class:

public class details
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Country { get; set; }
    public int Phone { get; set; }

    public string[] ToArr()
    {
        List<string> list = new List<string> { Id.ToString(), Name, Address, Country, Phone.ToString() };
        return list.ToArray();
    }
}

Result:

在此处输入图片说明

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