1 /*
2 * Copyright 2002-2009 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package net.sf.json;
18
19 import java.io.IOException;
20 import java.io.Writer;
21
22 /**
23 * JSONNull is equivalent to the value that JavaScript calls null, whilst Java's
24 * null is equivalent to the value that JavaScript calls undefined.
25 *
26 * @author JSON.org
27 */
28 public final class JSONNull implements JSON {
29 /** singleton instance */
30 private static JSONNull instance;
31
32 static{
33 instance = new JSONNull();
34 }
35
36 /**
37 * Returns the singleton instance of JSONNull
38 */
39 public static JSONNull getInstance() {
40 return instance;
41 }
42
43 private JSONNull() {
44
45 }
46
47 /**
48 * A Null object is equal to the null value and to itself.
49 *
50 * @param object An object to test for nullness.
51 * @return true if the object parameter is the JSONObject.NULL object or
52 * null.
53 */
54 public boolean equals( Object object ) {
55 return object == null || object == this || object == instance
56 || (object instanceof JSONObject && ((JSONObject) object).isNullObject())
57 || "null".equals( object );
58 }
59
60 public int hashCode() {
61 return 37 + "null".hashCode();
62 }
63
64 public boolean isArray() {
65 return false;
66 }
67
68 public boolean isEmpty() {
69 throw new JSONException( "Object is null" );
70 }
71
72 public int size() {
73 throw new JSONException( "Object is null" );
74 }
75
76 /**
77 * Get the "null" string value.
78 *
79 * @return The string "null".
80 */
81 public String toString() {
82 return "null";
83 }
84
85 public String toString( int indentFactor ) {
86 return toString();
87 }
88
89 public String toString( int indentFactor, int indent ) {
90 StringBuffer sb = new StringBuffer();
91 for( int i = 0; i < indent; i += 1 ){
92 sb.append( ' ' );
93 }
94 sb.append( toString() );
95 return sb.toString();
96 }
97
98 public Writer write( Writer writer ) {
99 try{
100 writer.write( toString() );
101 return writer;
102 }catch( IOException e ){
103 throw new JSONException( e );
104 }
105 }
106 }