@@ -130,33 +130,60 @@ public static JSONObject toJSONObject(String string) {
130130
131131 /**
132132 * Convert a JSONObject into a cookie specification string. The JSONObject
133- * must contain "name" and "value" members.
133+ * must contain "name" and "value" members (case insensitive) .
134134 * If the JSONObject contains other members, they will be appended to the cookie
135135 * specification string. User-Agents are instructed to ignore unknown attributes,
136136 * so ensure your JSONObject is using only known attributes.
137137 * See also: <a href="https://tools.ietf.org/html/rfc6265">https://tools.ietf.org/html/rfc6265</a>
138138 * @param jo A JSONObject
139139 * @return A cookie specification string
140- * @throws JSONException if a called function fails
140+ * @throws JSONException thrown if the cookie has no name.
141141 */
142142 public static String toString (JSONObject jo ) throws JSONException {
143143 StringBuilder sb = new StringBuilder ();
144-
145- sb .append (escape (jo .getString ("name" )));
144+
145+ String name = null ;
146+ Object value = null ;
147+ for (String key : jo .keySet ()){
148+ if ("name" .equalsIgnoreCase (key )) {
149+ name = jo .getString (key ).trim ();
150+ }
151+ if ("value" .equalsIgnoreCase (key )) {
152+ value =jo .getString (key ).trim ();
153+ }
154+ if (name != null && value != null ) {
155+ break ;
156+ }
157+ }
158+
159+ if (name == null || "" .equals (name .trim ())) {
160+ throw new JSONException ("Cookie does not have a name" );
161+ }
162+ if (value == null ) {
163+ value = "" ;
164+ }
165+
166+ sb .append (escape (name ));
146167 sb .append ("=" );
147- sb .append (escape (jo . getString ( "value" ) ));
168+ sb .append (escape (( String ) value ));
148169
149170 for (String key : jo .keySet ()){
150171 if ("name" .equalsIgnoreCase (key )
151172 || "value" .equalsIgnoreCase (key )) {
152173 // already processed above
153174 continue ;
154175 }
155- Object value = jo .opt (key );
176+ value = jo .opt (key );
156177 if (value instanceof Boolean ) {
157- sb .append (';' ).append (key );
178+ if (Boolean .TRUE .equals (value )) {
179+ sb .append (';' ).append (escape (key ));
180+ }
181+ // don't emit false values
158182 } else {
159- sb .append (';' ).append (key ).append ('=' ).append (escape (value .toString ()));
183+ sb .append (';' )
184+ .append (escape (key ))
185+ .append ('=' )
186+ .append (escape (value .toString ()));
160187 }
161188 }
162189
0 commit comments