I want to de-serialize a JSON where a node contains values which comma-separated. But the object which contains the comma returns null when deserializing.
Input JSON:
{
"SolutionTabletSubSectionUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"SolutionTabletSubSectionId": 1,
"SolutionTabletUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"Title": "string",
"SubTitle": "string",
"Description": "string",
"Link": "www.google.com,www.facebook.com",
"LinkDisplayName": "DisplayName1,DisplayName2",
"SolutionTabletConfigurationUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"SolutionTabletTemplateUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"ImageName": "string",
"ImagePath": "string",
"DisplayOrderId": 0,
"TemplateComponentUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"FooterTitle": "string",
"FooterDescription": "string"
}
Code:
var list = new List<MyList>();
list.Add(JsonConvert.DeserializeObject<MyClass>(input));
MySubClass resultSet = new MySubClass();
resultSet.Data = list;
MyClass:
public class MyClass
{
public Guid SolutionTabletSubSectionUId { get; set; }
public int SolutionTabletSubSectionId { get; set; }
public string LinkDisplayName { get; set; }
public string Link { get; set; }
public List<LinkNamesNode> LinkNames { get; set; }
}
public class LinkNamesNode
{
public string LinkDisplayName { get; set; }
public string Link { get; set; }
}
While debugging, I can see LinkNames
is set to null or not hitting because the property name is not found. Please help me here to deserialize an object.
My output should look like:
{
"LoggedInUser": "string",
"Data": [
{
"SolutionTabletSubSectionUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"SolutionTabletSubSectionId": 0
"LinkNames": [
{
"LinkDisplayName": "DisplayName1",
"Link": "www.google.com"
},
{
"LinkDisplayName": "DisplayName2",
"Link": "www.facebook.com"
}
]
]
}
Please assist.
3
Answers
You can work with
JsonConstructorAttribute
to implement the custom deserialization logic.Since mentioned that the size of
Link
andLinkDisplayName
may differ in length after split by separator:Get the max value between the
links
andlinkDisplayNames
arrays.Get the value from the array by index safely with
Array.ElementAtOrDefault(i)
method. And add the object to theLinkNames
array.you can solve this problem with an intermediate object because the structures of two side is not the same.
create a temp class:
public class MyTempClass
{
public Guid SolutionTabletSubSectionUId { get; set; }
public int SolutionTabletSubSectionId { get; set; }
Change your code to this:
string input = File.ReadAllText("C:working_dirstackoverflowsjsonserializeConsoleApp1ConsoleApp1jsconfig1.json");
MyTempClass result= JsonConvert.DeserializeObject(input);
MyClass myClass = result.ConverToMyClass();
Hope this helps.
you can create a json converter
and remove these properties from your class, you don’ t need them