1

I have got json:

{
  "_embedded": {
    "users": {
      "1688416": {
        "id": 1688416,
        "name": "test"
      },
      "1688395": {
        "id": 1688395,
        "name": "test",

      },
      "1625614": {
        "id": 1625614,
        "name": "test"      
      }
    }
  }
}

I should deserialize it by Newtonsoft.JSON library, but i can't undestand how to?? Object in "users" object can change, and "users" - is not array.

I can just JsonConvert.DeserializeObject(myobject) and take all fields by indexes, but it's stupidly, and i want to deserialize this json to normal object. How to?


UPDATE: code that i use

T is User

public class Response<T>
    {     
        [JsonProperty("_embedded", NullValueHandling = NullValueHandling.Ignore)]
        public EmbeddedContent<T> EmbeddedContent { get; set; }
    }

    public class EmbeddedContent<T>
    {
        [JsonPropertyNameBasedOnItemClass]
        public List<T> Items { get; set; }
    }

public class User{
    public int id{get;set;}
    public string name {get;set;}
}

JsonPropertyNameBasedOnItemClass - work like JsonProperty("users")

and try deserialize:

JsonConvert.DeserializeObject<Response<User>>(...)
1
  • what code are you using at the moment? Commented Apr 4, 2018 at 7:55

2 Answers 2

1

You can use the dictionary instead of the list

For example:

public class EmbeddedContent<T>
{
    [JsonProperty("users")]
    public Dictionary<string, T> Items { get; set; }
}

Then refer to user by ID

var response = JsonConvert.DeserializeObject<Response<User>>(json);
var user = response.EmbeddedContent.Items["1688416"];
Sign up to request clarification or add additional context in comments.

Comments

0

In the end, i found this solution:

var p = JObject.Parse(rawJson).SelectToken("_embedded.users").Children().Select(t => t.First.ToObject<User>());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.