How to Parse a Json String That Would Cause Illegal C# Identifiers

How can I parse a JSON string that would cause illegal C# identifiers?

You can deserialize to a dictionary.

public class Item
{
public string fajr { get; set; }
public string sunrise { get; set; }
public string zuhr { get; set; }
public string asr { get; set; }
public string maghrib { get; set; }
public string isha { get; set; }
}

var dict = JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);

How do I deserialise json to c# that is valid json but doesn't follow a standard object pattern as it has no base parameter pair

You need to deserialize to List<Dictionary<string, ThemeMyLogin>> like so:

var root = JsonConvert.DeserializeObject<List<Dictionary<string, ThemeMyLogin>>>(json);

The code-generation site http://json2csharp.com/ has some limitations of which you need to be aware:

  1. The JSON standard allows for two types of container:

    • The array, which is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

    • The object, which is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace).


    If your root container is an array, http://json2csharp.com/ will auto-generate a RootObject model to deserialize each object in the array. To actually deserialize the entire array you need to deserialize to a collection of root objects such as a List<RootObject>. See Serialization Guide: IEnumerable, Lists, and Arrays.

  2. When a JSON property corresponds to an invalid c# identifier, http://json2csharp.com/ will "helpfully" add a property to the containing type that looks like this:

    public PropertyType __invalid_name__my-invalid-identifier { get; set; }

    Of course this will not compile, so you need to notice any __invalid_name properties and manually fix the generated code. Options for doing this include those covered in How can I parse a JSON string that would cause illegal C# identifiers? and elsewhere:

    • If the property name is fixed and known in advance, rename the c# property to something valid consistent with your coding conventions and mark it with [JsonProperty("my-invalid-identifier")]. (From the answer by ken2k).

    • If the containing type consists entirely of variable property names with a fixed schema for their values corresponding to some type T, replace the containing type with a Dictionary<string, T>. (From the answer by L.B.)

    • If the containing object has a mixture of fixed and variable properties, see Deserialize json with known and unknown fields or How to deserialize a child object with dynamic (numeric) key names?.

You seem to have encountered both limitations. Working sample .Net fiddle.

Deserialize JSON Object to C# class after API call

Your biggest issue is that your model doesn't match your json string. You can use a dictionary to represent your data and your model would look something like this:

        public void Deserialize()
{
var obj = JsonConvert.DeserializeObject<RootObject>(json);
}

private string json = @"{""status"": ""ok"",
""meta"": {
""count"": 1,
""hidden"": null
},
""data"": {
""111111111"": [
{
""ship_id"": 4180588496
},
{
""ship_id"": 4284430032
},
{
""ship_id"": 3767482320
}
]
}
}";

public class RootObject
{
public string Status { get; set; }
public MetaData Meta { get; set; }
public IDictionary<string, IEnumerable<Ship>> Data { get; set; }
}

public class MetaData
{
public int Count { get; set; }
public string Hidden { get; set; }
}

public class Ship
{
public long Ship_Id { get; set; }
}

Parse JSON using c#

You can convert this json to c# class structure using a Dictionary to hold the merchants (where the ID is the string key):

public class RootObject
{
public string AppId { get; set; }
public Dictionary<string, List<ChildObject>> Merchants { get; set; }
}

public class ChildObject
{
public string ObjectId { get; set; }
public string Type { get; set; }
public long Ts { get; set; }
}

You can then loop over the childobjects like so:

foreach (var kvp in rootObject.Merchants) 
{
var childObjects = kvp.Value;
foreach (var childObject in childObjects) {
Console.WriteLine($"MerchantId: {kvp.Key}, ObjectId: {childObject.ObjectId}, Type: {childObject.Type}");
}
}

How to deserialize a pseudo-json array into c#

The data property of your JSON object is an associative array. You need to access each element by the appropriate key (in this case a numeric string)

// convert from a String into a JObject
var data = JObject.Parse(json);

// access single property
Response.Write(data["data"]["71489"]);
Response.Write(data["data"]["140141"]);

// iterate all properties
foreach (JProperty prop in data["data"])
{
Response.Write(prop.Name + ": " + prop.Value);

// Also possible to access things like:
// - prop.Value["air_by_date"]
// - prop.Value["cache"]["banner"]
// - prop.Value["cache"]["poster"]
// - prop.Value["language"]
}


Related Topics



Leave a reply



Submit