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