1
2
3
4
5
6
7
8
9
10 package org.mule.module.json;
11
12 import org.mule.tck.AbstractMuleTestCase;
13 import org.mule.util.IOUtils;
14
15 import org.codehaus.jackson.node.ArrayNode;
16 import org.codehaus.jackson.node.ObjectNode;
17
18 public class JsonDataTestCase extends AbstractMuleTestCase
19 {
20 public void testReadingArrayData() throws Exception
21 {
22 JsonData jsonData = readJsonData("test-data.json");
23 assertTrue(jsonData.isArray());
24 assertEquals("test from Mule: 6ffca02b-9d52-475e-8b17-946acdb01492", jsonData.get("[0]/text"));
25 assertEquals("test from Mule: 6ffca02b-9d52-475e-8b17-946acdb01492", jsonData.get("[0]/'text'"));
26
27 assertEquals("Mule Test", jsonData.get("[0]/'user'/name"));
28 assertEquals("Mule Test9", jsonData.get("[9]/user/name"));
29
30 assertNotNull(jsonData.toString());
31 try
32 {
33 assertNull(jsonData.get("[0]/user/XXX"));
34 fail("Property XXX does not exist");
35 }
36 catch (Exception e)
37 {
38
39 }
40 try
41 {
42 jsonData.get("foo[0]/user");
43 fail("foo is not the root element name");
44 }
45 catch (Exception e)
46 {
47
48 }
49
50 try
51 {
52 jsonData.get("[10]/user");
53 fail("Index should be out of bounds");
54 }
55 catch (Exception e)
56 {
57
58 }
59 }
60
61 public void testReadingComplexData() throws Exception
62 {
63 JsonData jsonData = readJsonData("filters.json");
64 assertFalse(jsonData.isArray());
65
66
67 assertEquals("teh ", jsonData.get("filters[1]/init[1][0]"));
68 assertEquals("the ", jsonData.get("filters[1]/init[1][1]"));
69
70 assertNotNull(jsonData.toString());
71 }
72
73 public void testReadingWithQuotedString() throws Exception
74 {
75 JsonData jsonData = readJsonData("bitly-response.json");
76 assertEquals("NfeyS", jsonData.get("results/'http://rossmason.blogspot.com/2008/01/about-me.html'/hash"));
77 }
78
79 public void testReadingArray() throws Exception
80 {
81 JsonData jsonData = readJsonData("flickr-response.json");
82
83 assertEquals("4136507840", jsonData.get("photos/photo[0]/id"));
84
85 ArrayNode photos = (ArrayNode) jsonData.get("photos/photo");
86 assertNotNull(photos);
87 assertEquals(10, photos.size());
88
89 Object o = jsonData.get("photos");
90 assertNotNull(o);
91 assertTrue(o instanceof ObjectNode);
92 }
93
94 private JsonData readJsonData(String filename) throws Exception
95 {
96 String json = IOUtils.getResourceAsString(filename, getClass());
97 return new JsonData(json);
98 }
99 }