Created
September 17, 2015 07:23
-
-
Save RavuAlHemio/a89466e89c6670d9893e to your computer and use it in GitHub Desktop.
Example of NewtonSoft.Json usage, JsonObject edition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
namespace JsonObjectExample | |
{ | |
[JsonObject(MemberSerialization.OptIn)] | |
class UserData | |
{ | |
[JsonProperty("username")] | |
public string Username { get; set; } | |
[JsonProperty("transactions")] | |
public List<Transaction> Transactions { get; set; } | |
} | |
[JsonObject(MemberSerialization.OptIn)] | |
class Transaction | |
{ | |
[JsonProperty("type")] | |
public string TransactionType { get; set; } | |
[JsonProperty("amount")] | |
public decimal Amount { get; set; } | |
[JsonProperty("paid")] | |
public bool IsPaid { get; set; } | |
} | |
class Test | |
{ | |
public static void Main() | |
{ | |
string jsonData = @"{ | |
""username"": ""hb2"", | |
""transactions"": [ | |
{ | |
""type"": ""plot"", | |
""amount"": 66.6, | |
""paid"": true | |
}, | |
{ | |
""type"": ""print"", | |
""amount"": 4.2, | |
""paid"": false | |
} | |
] | |
}"; | |
UserData userData = new UserData(); | |
using (StringReader reader = new StringReader(jsonData)) | |
{ | |
JsonSerializer.Create().Populate(reader, this); | |
} | |
// userData.Username == "hb2" | |
// userData.Transactions.Count == 2 | |
// userData.Transactions[0].TransactionType == "plot" | |
// userData.Transactions[0].Amount == 66.6m | |
// userData.Transactions[0].IsPaid == true | |
// userData.Transactions[1].TransactionType == "print" | |
// userData.Transactions[1].Amount == 4.2m | |
// userData.Transactions[1].IsPaid == false | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment