Hello,
Is it possible to add fields to an arbitrary JSON string/object? I need to modifiy a Solr configuration using their REST API and their format is a bit…special/unstructured so I cannot create a POCO.
For example, if I have this JSON object:
{
"Name": "Freddie",
"Age": 12,
"Favorite": ["a", "b"],
"Street": "47"
}
Is there a way to add a new field to this JSON without changing the structure? I tried using JsonObject to read the object and JsonSerializer however this method changes the Street
property from a string to a number which causes issues with the program that ultimately interpret the data (a Solr server):
{
"Name":"Freddie",
"Age":12,
"Favorite":["a", "b"],
"Street":47,
"NewField":"NewValue"
}
I tried deserializing the JSON to a Dictionary<string, object> which causes the Favorite
array to be mangled (it becomes "[a, b]"
). I also tried the DynamicJson
object however I had 2 issues with it:
- It looks like the string is read as a
Dictionary<string, string>
which causes issues with theStreet
property as with JsonObject - I was not able to serialize a dynamic object made from
DynamicJson
:
var str = @"{
""Name"": ""Freddie"",
""Age"": 12,
""Favorite"": [""a"", ""b""],
""Street"": ""47""
}";
var dynJs = DynamicJson.Deserialize(str);
var serializedValue = DynamicJson.Serialize(dynJs); // this value is always {}
- I should point out that serializing an anonymous object (
new { A = 3 }
) works as expected.
Is it possible to achieve what I want to do (adding a field without modifying the structure) or am I screwed? I realize this is a weird requirement. I added the real Solr
JSON below.
Thanks
{
"name":"/select",
"class":"solr.SearchHandler",
"defaults":{
"echoParams":"explicit",
"rows":10,
"df":"name",
"hl":"on",
"hl.fl":"name",
"f.name.hl.fragsize":"0",
"f.name.hl.alternateField":"name",
"spellcheck":"on",
"spellcheck.dictionary":[
"default",
"wordbreak"
],
"spellcheck.extendedResults":"false",
"spellcheck.count":"5",
"spellcheck.alternativeTermCount":"2",
"spellcheck.maxResultsForSuggest":"5",
"spellcheck.collate":"true",
"spellcheck.collateExtendedResults":"true",
"spellcheck.maxCollationTries":"5",
"spellcheck.maxCollations":"3"
},
"components":[
"query",
"tvComponent",
"highlight2",
"spellcheck3",
"debug"
]
}