I am trying to parse a JSON file into an object using Newtonsoft in my ASP.NET Core application but I keep getting this error:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: {. Path 'palette.swatch', line 7, position 15.'
I've tried using the StreamReader
class and now MemoryStream
class. I've confirmed validated the JSON online and checked it is UTF-8 too. Both ways I receive the same error. I also manually checked the JSON but I can't see anything that would make it unreadable.
Here's the method that is throwing the exception:
public async Task<int> PostDefinition(IFormFile file)
{
MemoryStream ms = new MemoryStream();
file.CopyTo(ms);
byte[] bytes = ms.ToArray();
string s = Encoding.UTF8.GetString(bytes);
Definition definition = Newtonsoft.Json.JsonConvert.DeserializeObject<Definition>(s);
Definition x = ObjectMapper.Map<Definition>(Definition);
return await _definitions.InsertAndGetIdAsync(x);
}
This is the segment of the JSON that is throwing an error:
{
"name": "Definition",
"id": 2,
"palette": {
"name": "Test Palette",
"default": false,
"swatch": {
"colors": {
"Color 1": "transparent",
"Color 2": "transparent",
"Color 3": "transparent",
"Color 4": "transparent",
"Color 5": "transparent",
"Color 6": "transparent",
"Color 7": "transparent",
"Color 8": "transparent"
}
}
}
}
What could be causing the exception and what can I try to remedy it? I've tried searching and nothing I try seems to work.
CodePudding user response:
this works for me
Definition definition = Newtonsoft.Json.JsonConvert.DeserializeObject<Definition>(s);
classes
public partial class Definition
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("palette")]
public Palette Palette { get; set; }
}
public partial class Palette
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("default")]
public bool Default { get; set; }
[JsonProperty("swatch")]
public Swatch Swatch { get; set; }
}
public partial class Swatch
{
[JsonProperty("colors")]
public Dictionary<string,string> Colors { get; set; }
}