質問

I have a class:

[DataContract]
public class A
{
    [DataMember]
    public B ArbitraryProperty { get; set;}
}

When serialized, "ArbitraryProperty" needs to be in the form of class "B":

[DataContract]
public class B
{
    [DataMember]
    public string ValueA { get; set; }
    [DataMember]
    public string ValueB { get; set; }
}

Here's the JSON output:

{
    "ArbitraryProperty": { "ValueA": "I'm a value.", "ValueB": "I'm a value too!" }
}

When I get that same object back from the server though, the property comes back as a simple string like this:

{
    "ArbitraryProperty": "I'm not a B, muahahaha!!!"
}

There has to be a trick to letting the DataContractJsonSerializer know that it should deserialize the value to a string instead of a "B".

Is there a special way to set up class "A"? :/

Any suggestions?

役に立ちましたか?

解決

I don't think this is the right way to go - I think the right answer for readability and usability is to properly type a request and a response class. But...Only thing I can think of is to make the property an object rather than strongly typing it. You'll just need to ensure that when you assign a value to it, you assign the right type.

public class A
{
    public object ArbitraryProperty { get; set; }
}

It will still serialize properly:

var a = new A { ArbitraryProperty = new B { ValueA = "a", ValueB = "b" } };
var json = JsonConvert.SerializeObject(a);
Console.WriteLine(json);

When the object comes back, deserializing will put that string into the property.

json = "{'ArbitraryProperty':'This is some string'}";
a = JsonConvert.DeserializeObject<A>(json);

This code works with simple serialize/deserialize from JSON.NET, but I don't know if WebAPI or whatever technology you're using will like it.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top