Search code examples
c#jsonpropertiesjson.net

C# Searching for a property and returning its value in Newtonsoft JSON.Net


I cannot serialize the data to C# object as the structure of JSON is not the same for same set of objects. Is there some kind of function that lets you search through all JSON properties and their child properties in order to return a value of the property you searched for?

Examples of the data I'm receiving through API (I'm trying to return the value of property "propertyIamLookingFor"):

First Example

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "propertyIamLookingFor": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    }
}} 

Second Example

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "propertyIamLookingFor": 32
}}

Third Example

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "window": {
            "title": "Sample Konfabulator Widget",
            "name": "main_window",
            "height": 500,
            "propertyIamLookingFor": 11
        }
    }
}} 

Notice that the property always has the same name regardless of its position, so I know the name of the property and I'm trying to return the value.

*In case anyone wonders, it is a bad API I'm accessing, but have no option to not working with it.


Solution

  • You can use JSONPath for this, it's similar to XPath.

    For example to find all properties called myProp use the JSONPath expression

    $..myProp

    This is a recursive selector that will iterate all properties and child props etc.

    if the property name contains non standard characters use this

    $..['my.Prop']

    JSONPath is built into the json.net library

    Take another look at http://newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm but dig deeper :)