Search code examples
c#jsonunit-testingdeserializationmstest

How to partially extract a JSON string to get a specific object by name


I have the following json string:

 "{"\"itemList\":[{\"id\":1,\"name\":\"Item 1 Name\"},{\"id\":2,\"name\":\"Item 2 Name\"}],"listInfo":{"info1":1,"info2":"bla"}}"

How can I extract specific objects into a string? For example, I want to get a new string out of it that looks like this:

[{\"id\":1,\"name\":\"Item 1 Name\"},{\"id\":2,\"name\":\"Item 2 Name\"}]

and another string that looks like this:

{"info1":1,"info2":"bla"}.

The first string represents the itemList object (which holds an array) and the second string represents the listInfo object.

My objective is to compare these strings to other other objects that I plan to serialize for unit testing.


Solution

  • First, create a DTO for your JSON string:

    class BaseClass
    {
        public List<ItemList> itemList = new List<ItemList>();
        public ListInfo listInfo = new ListInfo();
    }
    
    class ItemList
    {
        public string id { get; set; }
        public string name { get; set; }
    }
    
    class ListInfo
    {
        public string info1 { get; set; }
        public string info2 { get; set; }
    }
    

    Then: (after I fixed the JSON string format)

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    
    string jsonString = "{\"itemList\":[{\"id\":1,\"name\":\"Item 1 Name\"},{\"id\":2,\"name\":\"Item 2 Name\"}],\"listInfo\":{\"info1\":1,\"info2\":\"bla\"}}";
    
    BaseClass toCompare = JsonConvert.DeserializeObject<BaseClass>(jsonString);
    string itemList = JsonConvert.SerializeObject(toCompare.itemList);
    string listInfo = JsonConvert.SerializeObject(toCompare.listInfo);