Search code examples
c#jsonjsonserializer

how get all elements of array in deserialize json c#?


In C #, I have 5-6 days and I wanted to try to use the api one site. I have deserialize JSON and here is the format

[ { "uid": 1476402, "first_name": "", "last_name": "", "domain": "sandrische", "online": 1, "user_id": 1476402 }, { "uid": 3813182, "first_name": "", "last_name": "", "domain": "id3813182", "online": 0, "user_id": 3813182 }, { "uid": 12789624, "first_name": "", "last_name": "", "domain": "id12789624", "online": 0, "user_id": 12789624 }]

there is a class

 public class vkResponse
{
    [JsonProperty(PropertyName = "uid")]
    public int Id { get; set; }

    [JsonProperty(PropertyName = "first_name")]
    public string FirstName { get; set; }

    [JsonProperty(PropertyName = "last_name")]
    public string LastName { get; set; }

    [JsonProperty(PropertyName = "photo_50")]
    public Uri PhotoUri { get; set; }

    [JsonProperty(PropertyName = "online")]
    [JsonConverter(typeof(BoolConverter))]
    public bool IsOnline { get; set; }

    [JsonProperty(PropertyName = "lists")]
    public List<int> Lists { get; set; }

}


public class BoolConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(((bool)value) ? 1 : 0);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader.Value.ToString() == "1";
    }
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(bool);
    }
}

I want to get id

 var req = new HttpRequest();
        string resp = req.Get("https://api.vk.com/method/friends.get?user_ids=1&fields=domain&access_token=" + GetToken()).ToString();
       JObject o = JObject.Parse(resp);
        JArray array = (JArray)o["response"];
        vkResponse v = JsonConvert.DeserializeObject<vkResponse>(array.First().ToString());

        richTextBox1.Text = v.Id.ToString();

But I get only the first ID, how to get all ID? I think that the problem in this array.First().ToString() ? Please help or give an example.


Solution

  • Your response is an array of vkResponse classes, so you could deserialize it as a c# array:

    vkResponse[] vkResponses = JsonConvert.DeserializeObject<vkResponse[]>(array.ToString());
    

    Once you have the array you can loop through and access the IDs of each element.

    Pleaase , give me example how loop through and access the IDs of each elemen

    OK, here's a way to do it using elementary c# looping constructs and arrays:

        vkResponse[] vkResponses = JsonConvert.DeserializeObject<vkResponse[]>(array.ToString());
        if (vkResponses == null)
            throw new JsonException();
        int [] ids = new int[vkResponses.Length];
    
        for (int i = 0; i < vkResponses.Length; i++)
        {
            ids[i] = vkResponses[i].Id;
        }
    

    If you want to show the IDs as a comma-separated sequence of integers in the rich text box, you use the following method to generate the string:

        public static string ExtractVkResponseIds(string vkResponseJson)
        {
            vkResponse[] vkResponses = JsonConvert.DeserializeObject<vkResponse[]>(vkResponseJson);
            if (vkResponses == null)
                throw new JsonException();
            StringBuilder sb = new StringBuilder();
            // Format the ids as a comma separated string.
            foreach (var response in vkResponses)
            {
                if (sb.Length > 0)
                    sb.Append(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator);
                sb.Append(response.Id.ToString());
            }
            return sb.ToString();
        }
    

    and call it like:

        var req = new HttpRequest();
        string resp = req.Get("https://api.vk.com/method/friends.get?user_ids=1&fields=domain&access_token=" + GetToken()).ToString();
        JObject o = JObject.Parse(resp);
        JArray array = (JArray)o["response"];
        string ids = ExtractVkResponseIds(array.ToString());
        richTextBox1.Text = ids;
    

    I used the localized ListSeparator, by the way, which might not be a comma in your language. You can change it to a literal comma if you want.

    Your sample Json string is missing a closing bracket ("]"), by the way.