1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package net.sf.json.util;
18
19 import junit.framework.TestCase;
20 import net.sf.json.JSONFunction;
21 import net.sf.json.JSONObject;
22
23
24
25
26 public class TestJSONStringer extends TestCase {
27 public static void main( String[] args ) {
28 junit.textui.TestRunner.run( TestJSONStringer.class );
29 }
30
31 public TestJSONStringer( String testName ) {
32 super( testName );
33 }
34
35 public void testCreateArray() {
36 JSONBuilder b = new JSONStringer().array()
37 .value( true )
38 .value( 1.1d )
39 .value( 2L )
40 .value( "text" )
41 .endArray();
42 assertEquals( "[true,1.1,2,\"text\"]", b.toString() );
43 }
44
45 public void testCreateEmptyArray() {
46 JSONBuilder b = new JSONStringer().array()
47 .endArray();
48 assertEquals( "[]", b.toString() );
49 }
50
51 public void testCreateEmptyArrayWithNullObjects() {
52 JSONBuilder b = new JSONStringer().array()
53 .value( null )
54 .value( null )
55 .endArray();
56 assertEquals( "[null,null]", b.toString() );
57 }
58
59 public void testCreateEmptyObject() {
60 JSONBuilder b = new JSONStringer().object()
61 .endObject();
62 assertEquals( "{}", b.toString() );
63 }
64
65 public void testCreateFunctionArray() {
66 JSONBuilder b = new JSONStringer().array()
67 .value( new JSONFunction( "var a = 1;" ) )
68 .value( new JSONFunction( "var b = 2;" ) )
69 .endArray();
70 assertEquals( "[function(){ var a = 1; },function(){ var b = 2; }]", b.toString() );
71 }
72
73 public void testCreateSimpleObject() {
74 JSONBuilder b = new JSONStringer().object()
75 .key( "bool" )
76 .value( true )
77 .key( "numDouble" )
78 .value( 1.1d )
79 .key( "numInt" )
80 .value( 2 )
81 .key( "text" )
82 .value( "text" )
83 .key( "func" )
84 .value( new JSONFunction( "var a = 1;" ) )
85 .endObject();
86 JSONObject jsonObj = JSONObject.fromObject( b.toString() );
87 assertEquals( Boolean.TRUE, jsonObj.get( "bool" ) );
88 assertEquals( new Double( 1.1d ), jsonObj.get( "numDouble" ) );
89 assertEquals( new Long( 2 ).longValue(), ((Number) jsonObj.get( "numInt" )).longValue() );
90 assertEquals( "text", jsonObj.get( "text" ) );
91 assertTrue( JSONUtils.isFunction( jsonObj.get( "func" ) ) );
92 assertEquals( "function(){ var a = 1; }", jsonObj.get( "func" )
93 .toString() );
94 }
95 }