-
Notifications
You must be signed in to change notification settings - Fork 56
/
JsonDotNet.cs
74 lines (66 loc) · 2.21 KB
/
JsonDotNet.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Serialization
{
public class JsonDotNet
{
public static void Use()
{
var model = new SimpleData
{
Id = 42,
Names = new[] { "Bell", "Stacey", "her", "Jane" },
Location = new NestedData
{
LocationName = "London",
Latitude = 51.503209,
Longitude = -0.119145
},
Map = new Dictionary<string, int>
{
{ "Answer", 42 },
{ "FirstPrime", 2 }
}
};
string json = JsonConvert.SerializeObject(model, Formatting.Indented);
Console.WriteLine(json);
var deserialized = JsonConvert.DeserializeObject<SimpleData>(json);
var jo = (JObject)JToken.Parse(json);
Console.WriteLine(jo["Id"]);
foreach (JToken name in jo["Names"])
{
Console.WriteLine(name);
}
foreach (JToken loc in jo["Location"])
{
Console.WriteLine(loc);
}
int id = jo["Id"].Value<int>();
var names = (JArray)jo["Names"];
string firstName = names[0].Value<string>();
IEnumerable<JProperty> propsStartingWithLowerCase = jo.Descendants()
.OfType<JProperty>()
.Where(p => char.IsLower(p.Name[0]));
foreach (JProperty p in propsStartingWithLowerCase)
{
Console.WriteLine(p);
}
}
public class SimpleData
{
public int Id { get; set; }
public IList<string> Names { get; set; }
public NestedData Location { get; set; }
public IDictionary<string, int> Map { get; set; }
}
public class NestedData
{
public string LocationName { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
}
}
}