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
Make a modification in Myclass
and to the code block
There are multiple approaches here. Use
JsonIgnore
attribute on fields you don’t need:That will affect all usages thoug.
Create classes only with needed fields and map to them:
Or just using anonymous types:
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 viaJsonProperty
attribute.