Is it possible to parse json in a generic way without keys c#

Viewed 56

I want to parse json into an object, problem is I don't have the key names in the json, only the values. Is it possible to parse these values into an object?

Code example:

public class Test
{
    public uint one;
    public bool trueOrFalse;
    public uint three;
}

private void ParseTest()
{
    Test test = JsonConvert.DeserializeObject<Test>("[1, true, 3]");
}

Error I get using Newtonsoft.Json:

JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,true,3]) into type 'Test' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

Edit: What I want is to unfold the array onto an object's properties, in declaration order.

I work with a project where I get a lot of these value arrays and I cannot write a custom convert function for all of them. My first solution was a function that would insert the field names into the json before parsing, but this eventually broke when the json structure became more complicated (class in a class...).

1 Answers

your json is array, but you are trying to deserialize object. This code will work for you

var json="[1, true, 3]";
var jsonArray=JArray.Parse(json.Dump()).ToArray();

or if you want to convert to c# class

    Test test = new Test
    {
        one= (uint)jsonArray[0],
        trueOrFalse= (bool)jsonArray[1]
        three= (uint)jsonArray[2],
    }

this json will work for your class

var json = "{\"one\":1, \"trueOrFalse\":true, \"three\": 3}";
Test test = JsonConvert.DeserializeObject<Test>(json);
Related