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