Deserializing Object return empty object

Viewed 1019

I'm trying to read a file from a folder in my project and return the content as json.
This is my code:

string allText = System.IO.File.ReadAllText(jsonPath);
object jsonObject = JsonConvert.DeserializeObject(allText);
return Ok(jsonObject);

This is the file content:

[{"grouping":"IS3","count":327.0,"population":12.0,"weight":31.0},
{"grouping":"ISO","count":31.0,"population":31.0,"weight":27.0}]

This is the response from postman:
[
    [
        [
            []
        ],
        [
            []
        ]
    ]
]

If I put a break point I can see that the jsonObject is filled correctly.

I forgot to say I made the file with another endpoint reading from a file excel. The fields are not always the same, I made the object dinamicaly so I can't use a class.

I'd like to return a json as content type, not a text.

2 Answers

You are using JSON.Net to deserialise and not providing a type. This means it gets deserialised into JArray and JObject types. Then you are using the default serialiser of ASP.NET Core which is System.Text.Json, and that doesn't know what to do with the JSON.Net types which is why you get all those nested arrays. Stick with one method of serialising. You have various options, here's a couple:

  1. Use a proper class to deserialise and stick with System.Text.Json. This would be my preferred option.

    // Add these if missing:
    //using System.Text.Json;
    //using System.Text.Json.Serialization;
    
    public class MyThing
    {
        [JsonPropertyName("grouping")]
        public string Grouping { get; set; }
        [JsonPropertyName("count")]
        public double Count { get; set; }
        [JsonPropertyName("population")]
        public double Population { get; set; }
        [JsonPropertyName("weight")]
        public double Weight { get; set; }
    }
    

    And deserialise like this:

    var jsonObject = JsonSerializer.Deserialize<List<MyThing>>(allText);
    return Ok(jsonObject);
    

    Note: If you cannot create a class because the JSON is dynamic, you could fall back to using JsonSerializer.Deserialize<object>(allText)

  2. Send the JSON string back to the client manually

    return new JsonResult(jsonObject.ToString());
    

You need to model the type and desrialize the JSON. No need to add any property annotations. This should work

public class MyObject
{

    public string Grouping { get; set; }

    public double Count { get; set; }

    public double Population { get; set; }

    public double Weight { get; set; }
}

And then you can,

// read file into a string and deserialize JSON to a type
MyObject object1 = JsonConvert.DeserializeObject<List<MyObject>>(File.ReadAllText(@"c:\alltext.json"));
return Ok(object1);
Related