0

I have these entities:

public class Product
{
    public string Code {get;set;}
    public string Name {get;set;}

    public ICollection<Pack> Packs {get;set;}
}

public class Pack
{
    public string Colour {get;set;}
    public string Moq {get;set;}
}

my json object:

var products = [{
    code: 1243123,
    name: "Gel",
    packs: [{
        color: "blue",
        moq: 10
    }]
}];

note the naming differences, i.e. case and american spelling of color. Will the JavaScriptConvert.DeserializeObject() deserialise that correctly?

Or will I have to do it another way?

If I can just have an object where I can access those names directly and there values that would be great!

1
  • 1
    in your json packs is an array but in your Product class it's a single item, I think this will be an issue Commented Sep 16, 2013 at 10:09

2 Answers 2

2

If you use something like JSON.NET, then you can use attributes to control serialization, such as:

public class Pack
{
    [JsonProperty("color")]
    public string Colour {get;set;}
    [JsonProperty("moq")]
    public string Moq {get;set;}
}

Also, given your expected output, your Product class should look like this I think:

public class Product
{
    [JsonProperty("code")]
    public long Code {get;set;}
    [JsonProperty("name")]
    public string Name {get;set;}
    [JsonProperty("packs")]
    public Pack[] Packs {get;set;}
}

Note Code and Packs type.

Sign up to request clarification or add additional context in comments.

3 Comments

that seems really good, just means I cant change my model too much ;)
question: what if I literally just want the ids and one other field pulled out of that json object? the json object is used to make a table so I need all that information, however I cant be bother to write a parse to turn that data into a more simplified form, should I be bothered, will that make it easier, or can you just get the serialiser just to look at certain things?
No worries, I have implement a javascript function pulling out only the information i need, then I created c# objects that match identically, then got Newton JsonConvert.DeserialiseObject<>() to convert it, works a treat :)
1

If you use DataContractJsonSerializer instead, you can put attributes to your properties, giving them different names in generated/parsed JSON:

[DataContract]
public class Pack
{
    [DataMember(Name = "color")]
    public string Colour {get;set;}

    [DataMember(Name = "moq")]
    public string Moq {get;set;}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.