skip to Main Content

I have a Json value that I want to get only some part of it and ignore the other keys.

public class MyClass
{
    public long? id { get; set; }
    public Order order{ get; set; }
}

public class Order
{
    public long? id { get; set; }
    public int orderNo{ get; set; }
    public Customer customer{ get; set; }
}

List<MyClass> orderDetails= orderResult.Select(_ => new MyClass
              {
                 order= _.order
              }).ToList();

JArray res = JArray.FromObject(orderDetails);

res returns this:

{[ { "id": null, "order": { "id": 3, "orderNo": 12, "customer": { "id": 1 } } } ]}

But I want to get only this part:

{[ { "id": null, "order": { "id": 3 } ]}

2

Answers


  1. Make a modification in Myclass

    public class MyClass{
       public long? id { get; set; }
       public int orderNo{ get; set; }
    }
    

    and to the code block

        List<MyClass> orderDetails= orderResult.Select(_ => new MyClass
                      {id=_.order.id
                         order= _.order.orderNo
                      }).ToList();
    
    
    JArray res = JArray.FromObject(orderDetails);
    
    Login or Signup to reply.
  2. There are multiple approaches here. Use JsonIgnore attribute on fields you don’t need:

    public class Order
    {
        public long? id { get; set; }
        [JsonIgnore]
        public int orderNo{ get; set; }
        [JsonIgnore]
        public Customer customer{ get; set; }
    }
    

    That will affect all usages thoug.

    Create classes only with needed fields and map to them:

    public class MyClass
    {
        public long? id { get; set; }
        public OrderDTO order{ get; set; }
    }
    public class OrderDTO
    {
        public long? id { get; set; }
    }
    
    List<MyClass> orderDetails= orderResult
        .Select(o => new MyClass
        {
            order = new OrderDTO
            {
                id = o.id
            }
        })
        .ToList();
    

    Or just using anonymous types:

    var orderDetails = orderResult
        .Select(o => new
        {
            id = (long?)null,
            order = new
            {
                o.id
            }
        })
        .ToList();
    

    P.S.

    Use Common C# Coding Conventions, in this case Pascal casing for public properties. If you want to affect the serialization (i.e. use other convention then used for C#) there are multiple ways to achieve that in Newtonsoft Json.NET – you can use NamingStrategy or manually define property names via JsonProperty attribute.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search