2

I have a json string like this

{ "class": "go.GraphLinksModel",
  "nodeDataArray": [ {"key":"CTR:2", "type":"Controller", "devicename":"ACU-1K", "imageUrl":"../../../../Images/ComputerSpeaker_32.png", "loc":"295 97"} ],
  "linkDataArray": [  ]}

I created a class like this

public class FloorplanItem
{
    public string Class { get; set; }
    public string[] NodeDataArray { get; set; }
    public string[] LinkDataArray { get; set; }        
}

I'm using newtonsoft.json to deserialize the json to an object but I'm getting some errors

JsonConvert.DeserializeObject<FloorplanItem>(json)

Error message:

{"Error reading string. Unexpected token: StartObject. Path 'nodeDataArray[0]', line 2, position 23."}

I'm still pretty new to json, so please pardon me if this is trivial.

Null Reference
  • 11,260
  • 40
  • 107
  • 184

2 Answers2

3

Use http://json2csharp.com/. Copy the json there and you will get the following class:

public class NodeDataArray
{
    public string key { get; set; }
    public string type { get; set; }
    public string devicename { get; set; }
    public string imageUrl { get; set; }
    public string loc { get; set; }
}

public class RootObject
{
    public string @class { get; set; }
    public List<NodeDataArray> nodeDataArray { get; set; }
    public List<object> linkDataArray { get; set; }
}

The above class will be compliant with Json.NET

Habib
  • 219,104
  • 29
  • 407
  • 436
  • Great, didn't know there was such a tool. If you don't mind answering my comment, is json case sensitive? i.e., if my json property is devicename, but in my C# class, I have DeviceName, is that alright? – Null Reference Mar 28 '13 at 11:36
  • Not really sure, You can read about it here, http://stackoverflow.com/questions/11266695/json-net-case-insensitive-property-deserialization and also can check it with a simple json in your code – Habib Mar 28 '13 at 11:40
  • 1
    JSON.NET is case insensitive by default. Alternatively, you can annotate your properties with an attribute: `[JsonProperty("overriddenPropertyName")]` – fjdumont Mar 28 '13 at 12:02
1

Your NodeDataArray is defined as an array of strings, while your JSON document clearly defines it as an object.

Also, with Web Essentials 2012 you can perform a special paste called Paste JSON As Classes that will generate the desired CLR classes for you:

Paste JSON As Classes

public class FloorplanItem
{
    public string Class { get; set; }
    public NodeDataArray[] NodeDataArray { get; set; }
    public object[] LinkDataArray { get; set; }
}

public class NodeDataArray
{
    public string Key { get; set; }
    public string Type { get; set; }
    public string DeviceName { get; set; }
    public string ImageUrl { get; set; }
    public string Loc { get; set; }
}

Deserialization seems to work perfectly (notice I have fixed the property names to obey the common naming guidelines).

Watch

fjdumont
  • 1,517
  • 1
  • 9
  • 22