Question

I am using a REST service and it returns json formatted like this:

{
"ea:productionId": "123",
....
}

How can I create a class at server side corresponding to this type of json for parsing? I am using c#.

EDIT I am using C#2.0 This is the code I am using

JavaScriptSerializer serializer = new JavaScriptSerializer();
        JsonClass result= serializer.Deserialize<JsonClass>(jsonresult);

JsonClass is the class I have created with the fields corresponding to the attributes in the jsonresult. And the problem is, I can't create a property with name ea:productionId as it contains :.

Was it helpful?

Solution

What you have shown in your question is invalid JSON. I guess you meant this:

{
    "ea:productionId": "123",
    ....
}

which is pretty easy to achieve with Json.NET serializer using [DataContract] and [DataMember] attributes on your model:

[DataContract]
public class JsonClass
{
    [DataMember(Name = "ea:productionId")]
    public string ProductId { get; set; }
}

and then:

JsonClass result = JsonConvert.DeserializeObject<JsonClass>(jsonresult);

If you don't want to use third party JSON serializers you could use the built-in DataContractJsonSerializer class which also respects the DataContract and DataMember attributes:

var serializer = new DataContractJsonSerializer(typeof(JsonClass));
byte[] data = Encoding.UTF8.GetBytes(jsonresult);
using (var stream = new MemoryStream(data))
{
    var result = (JsonClass)serializer.ReadObject(stream);
}

UPDATE:

It looks like you are using .NET 2.0 and cannot rely on the newer serializers. With the JavaScriptSerializer you have the possibility to write a custom converter:

public class MyJavaScriptConverter : JavaScriptConverter
{
    private static readonly Type[] supportedTypes = new[] { typeof(JsonClass) };

    public override IEnumerable<Type> SupportedTypes
    {
        get { return supportedTypes; }
    }

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        if (type == typeof(JsonClass))
        {
            var result = new JsonClass();
            object productId;
            if (dictionary.TryGetValue("ea:productionId", out productId))
            {
                result.ProductId = serializer.ConvertToType<string>(productId);
            }

            ... so on for the other properties

            return result;
        }

        return null;
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

and then:

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new MyJavaScriptConverter() });
var result = serializer.Deserialize<JsonClass>(jsonresult);

alternatively you could use a weakly typed dictionary instead of the model:

var serializer = new JavaScriptSerializer();
var res = (IDictionary<string, object>)serializer.DeserializeObject(jsonresult);
string productId = res["ea:productionId"] as string;

OTHER TIPS

json is actually similar to a dictionary(key-value pairs) in python. You cannot write your key without quotes. Your key should actually be a string via which you can refer its values. Yours is invalid json.

Try this :

{
"ea:productionId": "123",
....
}

OR you can try this also(assuming your's is a dictionary inside a dictionary)

{
"ea":{"productionId": "123",}
....
}

So to have an access to value "123" , use ["ea"]["productionId"]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top