-1

Let's say I have a json string that looks like this:

{
  "customers": [{
      "id": 1,
      "name": "Bob"
    },
    {
      "id": 2,
      "name": "Mary"
    }
  ],
  "products": [{
      "id": 1,
      "description": "apple",
      "price": 0.50
    },
    {
      "id": 2,
      "description": "orange",
      "price": 0.75
    }
  ]
}

And from that string, I need to get a List<customer>:

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Maybe I'm missing something, but I'm not seeing in the Newtonsoft docs how to do this.

Casey Crookston
  • 13,016
  • 24
  • 107
  • 193
  • Possible duplicate of [Deserialize only one property of a JSON file](https://stackoverflow.com/questions/44701646/deserialize-only-one-property-of-a-json-file) – Heretic Monkey Nov 07 '19 at 19:42

2 Answers2

2
public class Customer
{
    public int id { get; set; }
    public string name { get; set; }
}

public class Product
{
    public int id { get; set; }
    public string description { get; set; }
    public double price { get; set; }
}

public class RootObject
{
    public List<Customer> customers { get; set; }
    public List<Product> products { get; set; }
}

Deserialize your json string into "RootObject"

var rootObj = JsonConvert.DeserializeObject<RootObject>(myJsonString);
Charles
  • 2,721
  • 1
  • 9
  • 15
2

You're looking for partial JSON fragment deserialization. All in all you have to load the whole JSON object into a JObject, then select child tokens of that object to convert into the desired type.

Also take a look at JSON path selection in which you can use token selectors to directly get a part of a JSON.

Martin Frøhlich
  • 602
  • 6
  • 10