I have a JSON object with multiple classes and values as shown below:
{
"Class 1": [
{
"Key1": "value1",
"Key2": "value3"
},
{
"Key3": "value3",
"Key4": "value4"
}
],
"Class 2": [
{
"Key11": "value11",
"Key21": "value31"
},
{
"Key31": "value31",
"Key41": "value41"
}
],
"Class 3": [
{
"Key112": "value112",
"Key212": "value312"
},
{
"Key312": "value312",
"Key412": "value412"
}
],
"Class 4": [
{
"Key12": "value12",
"Key22": "value32"
},
{
"Key32": "value32",
"Key42": "value42"
},
{
"Key321": "value321",
"Key421": "value421"
}
]
}
I wanted to remove certain classes entirely and get the rest class in a JSON Object. i.e, I want to take only Class 2 and Class 4 from that Object. Could anyone help me achieve this? Thanks in advance. The expected output is shown below:
{
"Class 2" : [
{
"Key11": "value11",
"Key21": "value31"
},
{
"Key31": "value31"
"Key41": "value41"
}
],
"Class 4" : [
{
"Key12": "value12",
"Key22": "value32"
},
{
"Key32": "value32"
"Key42": "value42"
},
{
"Key321": "value321"
"Key421": "value421"
}
]
}
3
Answers
First, your JSON is invalid, there are some missing commas.
Your JSON should be as:
And your JSON is an object, or also can be recognized as
Dictionary<string, List<object>>
type.Concept:
Dictionary<string, List<object>>
type.x.Key
byremainedKeys
.Dictionary
/key-value pair.Sample Program
Even as the @Yong Shun answer is the correct way to do it (mapping the Object)
You can take a roundabout and do a Deep clone serializing/deserializing (it could seem be a little hacky, but it works)
then you can serialize (again) result and obtain a JSON text to send to your file
Example classes definition:
try this