Home > database >  How to handle dictionary with different value type
How to handle dictionary with different value type

Time:12-16

I have a case where network call will retrieve json string. And it is like

"{"PdfSearchCTTestExperiment": 0, "_ecs": {"PdfSearchCTTestExperiment": "P-X-100967-1-13"}}"

Basically, the response will have two value types, one is string and another one is dictionary<string, string>.

And I need to deserilize both inner and outer key value pairs into dictionary. Here is my way of doing it:

var outerDict = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(ss);

string innerDictString = JsonConvert.SerializeObject(outerDict["_ecs"]);

var innerDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(innerDictString );

It works, but I do not feel it is the efficient way. Baiscally, because of the type system, I need to do like two more times parsing. Any better way to achieve this? Thanks!

CodePudding user response:

You can create a model for your response, something like:

public class ResponseModel 
{
   public int PdfSearchCTTestExperiment{get;set;}
   [JsonProperty("_ecs")]
   public Dictionary<string,string> Ecs{get;set;}
}

and deserialize it like so:

var responseModel = JsonConvert.DeserializeObject<ResponseModel>(ss);
Console.WriteLine(responseModel.Ecs["PdfSearchCTTestExperiment"]);

CodePudding user response:

Does Dictionary<string,object> suits your need? Then you can cast back to needed type though reflection

CodePudding user response:

json

{
    "PdfSearchCTTestExperiment": 0,
    "key1": "value1",
    "key2": "value2",
    "_ecs": {
        "PdfSearchCTTestExperiment": "P-X-100967-1-13"
    }
}

The easiest way to reach what you really need is json parsing, instead of deserialiazation

var jsonObject = JObject.Parse(json);

test

string key1= (string) jsonObject["key1"];
string pdfSearchCTTestExperiment= (string)jsonObject["_ecs"]["PdfSearchCTTestExperiment"];

if you still want to deserialiaze into 2 dictionaries instead of parsing, you will have to create a class

public class Dictionaries
{
    public Dictionary<string, string> OuterDict { get; set; }

    public Dictionary<string, string> InnerDict { get; set; }
}

code

var jsonObject = JObject.Parse(json);

var dictionaries = new Dictionaries{
OuterDict = jsonObject.Properties().Where(o => o.Name != "_ecs").ToDictionary(o => o.Name, o => (string)o.Value),
InnerDict = jsonObject.Properties().Where(o => o.Name == "_ecs").FirstOrDefault().Value.ToObject<Dictionary<string, string>>()
};

test

string key1=dictionaries.OuterDict["key1"];
string pdfSearchCTTestExperiment= dictionaries.InnerDict["PdfSearchCTTestExperiment"];
  • Related