0

I have the next issue: I receive a lot of JSONs in different formats. I need to process only part of these documents. I tried to use Newtonsoft.Json.Schema nuget, but got the next problem:
JSON how to don't parse additional properties

Can you suggest me some ways to parse only part of the JSON document, when we don't know structure of this json? We can store some schema of the document.

Example:
We have the next JSON document.
And here we need to process, for example, only name and age properties. And I will know these properties only in runtime.

{
   'name': 'James',
   'age': 29,
   'salary': 9000.01,
   'jobTitle': 'Junior Vice President'
}
Hanna Holasava
  • 192
  • 1
  • 15
  • Please add a tag for the language/technology you are using. – Alex K. May 24 '21 at 14:33
  • That's not [valid JSON](https://jsonlint.com/?json={%27invalid_json%27:true}). [Valid JSON](https://jsonlint.com/?json={%22valid_json%22:true}) uses double-quotes, not single quotes. Please keep that in mind so you don't code yourself into a corner. – Andy May 24 '21 at 14:39
  • Also, you can deserialize to `dynamic`. – Andy May 24 '21 at 14:44
  • @Andy yes, but how will I take then only part of all fields? – Hanna Holasava May 24 '21 at 14:45
  • 1
    `var obj = JsonConvert.DeserializeObject(jsonData); var name = (string)obj.name; var age = (int)obj.age;` – Andy May 24 '21 at 14:53
  • @Andy But the issue is we don't know at compile step field names. We will know the list of needed fields only in runtime. I like the second answer in this question: https://stackoverflow.com/questions/67672198/using-a-json-schema-how-can-i-filter-out-additional-properties-when-parsing-jso – Hanna Holasava May 24 '21 at 14:57
  • Are you looking to select only some sub-object of the root object, or are you looking to filter (nested) properties from the root object? If the latter, one possibility would be to use `JsonExtensions.RemoveAllExcept(this TJToken obj, IEnumerable paths) where TJToken : JToken` from [this answer](https://stackoverflow.com/a/30333562/3744182) to [How to perform partial object serialization providing “paths” using Newtonsoft JSON.NET](https://stackoverflow.com/q/30304128/3744182). – dbc May 24 '21 at 15:15
  • Also possibly related or duplicate: [Using JSONPath to filter properties in JSON documents](https://stackoverflow.com/q/57495394/3744182). – dbc May 24 '21 at 15:18

1 Answers1

0

If your json does not contain nested fields, so each of the top level fields are primitive types (not objects) then you can deserialize it as Dictionary<string, object> like this:

var fieldValueMap = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

string fieldName = "name";
Console.WriteLine(fieldValueMap.ContainsKey(fieldName) 
     ? fieldValueMap[fieldName] 
     : "There is no such field");
Peter Csala
  • 17,736
  • 16
  • 35
  • 75