Maryam
Maryam

Reputation: 515

Retrieve JSON object till level 1

I'm reading data from database and converting it to a JSON object which have multiple collections and multiple levels but I only want to retrieve json till level 1 and no related collections or data. I've used following line of code in C# for that purpose

var json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings() { MaxDepth = 1, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

Above line is returning following

{
  "abc": [
    {
      "Id": "TEST-06",
      "No": 1,
      "Code": " ",
      "Description": ".....",
      "Percentage": null,
      "Details": []
    }
  ],
  "xyz": {
    "Id": "TEST-06",
    "No.": 1,
    "Date": "2018/07/06",
    "Enable": 0,
    "Reason": "....."
  }
}

I only want the object "abc" but it's also returning xyz. I searched everywhere and they say use max depth property to serialize json object to specific depth. Can anyone please help with that?

Upvotes: 1

Views: 1066

Answers (1)

Sh.Imran
Sh.Imran

Reputation: 1033

You can get only "abc" object simply by using JObject property:

var jObject = JObject.Parse(YourJSonString);
var abcObject = jObject.First;

Update for Without "abc" Object

Create a class with any name for the JSon main object.

public class AnyClass
{
    public string Id { get; set; }
    public long No { get; set; }
    public string Code { get; set; }
    public string Description { get; set; }
    public object Percentage { get; set; }
    public List<object> Details { get; set; }
    public List<object> xyz { get; set; }
}

Deserialize your JSon string with this class type:

var deserializeObject = JsonConvert.DeserializeObject<AnyClass>(jsonString);

Now in deserializeObject, you would have all properties and xyz object.

Upvotes: 1

Related Questions