0

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.

Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62
voodooSHA A
  • 73
  • 1
  • 7
  • Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'WindowsFormsApplication30.vkResponse' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection – voodooSHA A Aug 24 '14 at 18:17
  • If you're using this through an asp.net web-api controller you can simply take this as an argument to the action and the serializer should sort it for you automatically. Meaning void myaction([FromBody] vkResponse[] responses) – Gaute Løken Aug 24 '14 at 18:19

2 Answers2

1
var v = JsonConvert.DeserializeObject<IEnumerable<vkResponse>>(array.ToString());

var userids = v.Select(x=>x.id);
Giannis Paraskevopoulos
  • 18,261
  • 1
  • 49
  • 69
  • Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'WindowsFormsApplication30.vkResponse'. An explicit conversion exists (are you missing a cast?) C:\Users\Pc\documents\visual studio 2012\Projects\WindowsFormsApplication30\WindowsFormsApplication30\Form1.cs 31 28 WindowsFormsApplication30 – voodooSHA A Aug 24 '14 at 18:18
  • Thx. But how to access the ID property? – voodooSHA A Aug 24 '14 at 18:26
  • If i am use `var userid = v.First().Id;` still get first ID , but i want get all Id's – voodooSHA A Aug 24 '14 at 18:31
  • Yes, can you check now? – Giannis Paraskevopoulos Aug 24 '14 at 18:33
  • `var v = JsonConvert.DeserializeObject>(array.ToString()); var userids = v.Select(x => x.Id); richTextBox1.Text = userids.ToString();` turned `System.Linq.Enumerable+WhereSelectListIterator2[WindowsFormsApplication30.vkResponse,System.Int32]` – voodooSHA A Aug 24 '14 at 18:38
0

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.

dbc
  • 104,963
  • 20
  • 228
  • 340