public void simpleTest() { //Create a simple JSON object JSONObject json1 = new JSONObject("{id:1, \"name\": \"Chris Richards\"}"); Assert.AreEqual(1, json1["id"], "Getting int with indexer"); Assert.AreEqual("Chris Richards", json1["name"], "Getting string with indexer"); Assert.IsNull(json1["rank"], "Keys that don't exist should return null"); Assert.AreEqual("1", json1.stringForKey("id"), "stringForKey should convert type if possible"); Assert.AreEqual("Chris Richards", json1.stringForKey("name"), "Getting string with stringForKey"); Assert.AreEqual(string.Empty, json1.stringForKey("rank"), "stringForKey should return empty if the key doesn't exist"); Assert.AreEqual(1, json1.intForKey("id"), "intForKey should return an int"); Assert.Throws<FormatException>(delegate() { json1.intForKey("name"); }, "Exception if convert fails."); Assert.AreEqual(0, json1.intForKey("rank"), "Zero if key not found"); }
public void typeTest() { //Create a JSON object with all the types JSONObject json1 = new JSONObject("{id:1, \"name\": \"Chris Richards\", isTrue:true, isFalse:false, list:[true, false, null], object:{gum:\"Trident\", type:\"Spearmint\"}}"); Assert.AreEqual(1, json1.intForKey("id")); Assert.AreEqual("Chris Richards", json1.stringForKey("name")); Assert.IsTrue(json1.boolForKey("isTrue")); Assert.IsFalse(json1.boolForKey("isFalse")); Assert.IsInstanceOf(typeof(System.Collections.Generic.List<object>), json1.listForKey("list")); Assert.IsInstanceOf<JSONObject>(json1.objectForKey("object")); System.Collections.Generic.List<object> list = json1.listForKey("list"); Assert.AreEqual(3, list.Count); Assert.AreEqual(true, list[0]); Assert.AreEqual(false, list[1]); Assert.AreEqual(null, list[2]); JSONObject obj = json1.objectForKey("object"); Assert.AreEqual("Trident", obj.stringForKey("gum")); Assert.AreEqual("Spearmint", obj.stringForKey("type")); }