0

This is a newbie question. I'm stuck with trying to deserialize a JSON object from a file to C# class object.

My JSON object looks this:

{
  "text": {
    "@fontName": "Helvetica",
    "@fontSize": "9.0",
    "@x": "629",
    "@y": "67",
    "@width": "126",
    "@height": "9",
    "#text": "844-4TX-4PMP (844-489-4767)"
  }
}

Below code deserializes JSON retrieved from a file

    using (StreamReader file = File.OpenText(Path.Combine(appDirectory, "json1.json")))
    {
        JsonSerializer serializer = new JsonSerializer();
        text textObj = (text)serializer.Deserialize(file, typeof(text));
    }

My C# object looks like this:

[JsonObject]
class text
{
    [JsonProperty(PropertyName = "@fontName")]
    public string FontName { get; set; }

    [JsonProperty(PropertyName = "@fontSize")]
    public string FontSize { get; set; }

    [JsonProperty(PropertyName = "@x")]
    public string X { get; set; }

    [JsonProperty(PropertyName = "@y")]
    public string Y { get; set; }

    [JsonProperty(PropertyName = "@width")]
    public string Width { get; set; }

    [JsonProperty(PropertyName = "@height")]
    public string Height { get; set; }

    [JsonProperty(PropertyName = "#text")]
    public string Text { get; set; }
}

I get null values returned after the object is deserialized. Can someone help point to what I'm doing wrong?

Thanks,

Ahmed Mujtaba
  • 2,110
  • 5
  • 36
  • 67
  • 1
    your JSON is an object with an inner property called "text", and it's that inner property which contains the values you're after. They're not at the root of the object where the deserialiser is expecting them. The overall object is not itself an object which would deserialise to your "text" type. If the JSON was simply `{ "@fontName": "Helvetica", "@fontSize": "9.0", "@x": "629", "@y": "67", "@width": "126", "@height": "9", "#text": "844-4TX-4PMP (844-489-4767)" }` I think that would work – ADyson Aug 15 '17 at 09:51
  • @ADyson it does indeed. Post this as answer so I can mark it. Thanks – Ahmed Mujtaba Aug 15 '17 at 09:54
  • Since it's subsequently been marked as a duplicate, I can't unfortunately. The duplicate contains more or less the same suggestion though – ADyson Aug 15 '17 at 09:55
  • Check this out: http://json2csharp.com/ --- hm, it's complaining about the `@`s in the name though. – Efrain Aug 15 '17 at 10:01

0 Answers0