私のJSONが次の場合:
{ cat: 1, dog: 2, price: { initial: 1, new: 2 } }
プロパティcat、dog、initialprice、newpriceを持つ単一のクラスに逆シリアル化することは可能ですか?
おそらく、これを行うために JsonProperty 属性を使用する属性または方法があります。
Newtonsoft.Json ライブラリを使用しています。
以下は少しラフで準備ができていますが、あなたがやろうとしていると私が思うことをします. ケーシングは JSON とは異なるため、変更を加えないと入力に往復することはありません。
public class TestClass
{
public decimal Cat { get; set; }
public decimal Dog { get; set; }
[Newtonsoft.Json.JsonProperty]
private Price Price { get; set; }
[Newtonsoft.Json.JsonIgnore]
public decimal InitialPrice
{
get { return this.Price.Initial; }
}
[Newtonsoft.Json.JsonIgnore]
public decimal NewPrice
{
get { return this.Price.New; }
}
}
class Price
{
public decimal Initial { get; set; }
public decimal New { get; set; }
}
クイックテスト方法:
static void Main(string[] args)
{
const string JSON = "{ cat: 1, dog: 2, price: { initial: 1, new: 2 } }";
var deserialised = Newtonsoft.Json.JsonConvert.DeserializeObject<TestClass>(JSON);
var serialised = Newtonsoft.Json.JsonConvert.SerializeObject(deserialised);
}
JSON の price プロパティから自然に逆シリアル化されるものと一致するように Price 型を定義し、それを非公開にしてから、TestClass の 2 つの読み取り専用プロパティを使用してそのメンバーにアクセスしました。つまり、コードは、定義した JSON 入力から解析された必要な構造 (Cat、Dog、InitialPrice、NewPrice の 4 つのプロパティ) を確認します。