1

I look for a method to deserialize JSON, but some keys should be values and it's where it gets tricky. I like to Deserialize to:

int valuetoExtract1
int valuetoExtract2
int valuetoExtract3

JSON looks like this:

{
    "option1": "someOption1",
    "option12": "someOption2",
    "id": [
        "12345"
    ],
    "filter": "someFilter",
    "actualValues": [
        {
            "otherId": 24,
            "id": 12345,
            "valuetoExtract1": "123"
        },
        {
            "otherId": 24,
            "id": 12345,
            "valuetoExtract2": "234"
        },
        {
            "otherId": 24,
            "id": 12345,
            "valuetoExtract3": "345"
        }
    ]
}
3
  • 2
    What have you tried so far? Commented Aug 31, 2019 at 8:53
  • 1
    tried JsonConvert.DeserializeObject to pre-generated class but I get new object with all variables for each valuetoExtract, variable that match valuetoExtrace get value and rest are null, also tried jObject and deserialize to Dictionary<string,string> but it would not work either Commented Aug 31, 2019 at 9:07
  • 1
    try json2csharp.com Commented Aug 31, 2019 at 9:52

4 Answers 4

1

You can prepare a dictionary using following method:

        static Dictionary<string, string> GetExtracts(string jsonText)
        {
            var valuetoExtractList = new Dictionary<string, string>();
            using (var reader = new JsonTextReader(new StringReader(jsonText)))
            {
                while (reader.Read())
                {
                    if (reader.TokenType.ToString().Equals("PropertyName")
                       && reader.ValueType.ToString().Equals("System.String")
                       && reader.Value.ToString().StartsWith("valuetoExtract"))
                    {
                        var key = reader.Value.ToString();
                        reader.Read();
                        valuetoExtractList.Add(key, reader.Value.ToString());
                    }
                }
            }

            return valuetoExtractList;
        }

Adapted based on Filter json properties by name using JSONPath

Sign up to request clarification or add additional context in comments.

Comments

1

can you try this:

public class ActualValue
{
    public int otherId { get; set; }
    public int id { get; set; }
    public string valuetoExtract1 { get; set; }
    public string valuetoExtract2 { get; set; }
    public string valuetoExtract3 { get; set; }
}

public class RootObject
{
    public string option1 { get; set; }
    public string option12 { get; set; }
    public List<string> id { get; set; }
    public string filter { get; set; }
    public List<ActualValue> actualValues { get; set; }
}

1 Comment

I did but each ActualValue object in actualValues list have full scope ActualValue properties which is a bit unmanagable and the if You want to get value for specific property You have to pick correct object from the list. So if sequence of JSON message change You don't know which one to pick as oll of
1

ended with something like this, not the prettiest but the best I could find so far:


public class ActualValue
{
    public int valuetoExtract1 { get; set; }

}

ActualValues actualValues = new ActualValues();
JObject jsonO = JObject.Parse(json);
var converterJsonO = jsonO["actualValues"];
var oList = converterJsonO .Children();

foreach(JObject childObject in oList)
    {
        var d = childObject.ToObject<Dictionary<string, string>>();
        if (d.ContainsKey("valuetoExtract1")) { actualValues.valuetoExtract1= int.Parse(d["valuetoExtract1"]); }
    }

Comments

0

You get the JSON result as a string, so it might be easier for you to remove all the numbers from valuetoExtract. For that you could use Regex.Replace() from System.Text.RegularExpressions namespace. Then you can use a single property for valuetoExtract key.

So your code can look like this:

var jsonString = "{ 'option1': 'someOption1','option2': 'someOption2','id': ['12345'],'filter': 'someFilter','actualValues': [{'otherId': 24,'id': 12345,'valuetoExtract129': '123'},{'otherId': 24,'id': 12345,'valuetoExtract2': '234'},{'otherId': 24,'id': 12345,'valuetoExtract3': '345'}]}";

jsonString = Regex.Replace(jsonString, @"valuetoExtract[0-9]*", "valuetoExtract");
ApiResult result = JsonConvert.DeserializeObject<ApiResult>(jsonString);

Where ApiResult is defined as the following

class ApiResult
{
    [JsonProperty(propertyName: "option1")]
    public string Option1 { get; set; }

    [JsonProperty(propertyName: "option2")]
    public string Option2 { get; set; }

    [JsonProperty(propertyName: "id")]
    public string[] Id { get; set; }

    [JsonProperty(propertyName: "filterd")]
    public string Filter { get; set; }

    [JsonProperty(propertyName: "actualValues")]
    public ActualValue[] ActualValues { get; set; }
}

class ActualValue
{
    [JsonProperty(propertyName: "id")]
    public int Id { get; set; }

    [JsonProperty(propertyName: "otherId")]
    public int OtherId { get; set; }

    [JsonProperty(propertyName: "valuetoExtract")]
    public int ValueToExtract { get; set; }
}

Comments