All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.minidev.json.JSONArray Maven / Gradle / Ivy

Go to download

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

There is a newer version: 1.3.2
Show newest version
package net.minidev.json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * A JSON array. JSONObject supports java.util.List interface.
 * 
 * @author FangYidong
 * @author Uriel Chemouni 
 */
public class JSONArray extends ArrayList implements List {
	private static final long serialVersionUID = 9106884089231309568L;

	/**
	 * Convert a list to JSON text. The result is a JSON array. If this list is
	 * also a JSONAware, JSONAware specific behaviours will be omitted at this
	 * top level.
	 * 
	 * @see net.minidev.json.JSONValue#toJSONString(Object)
	 * 
	 * @return JSON text, or "null" if list is null.
	 */
	public static String toJSONString(List list) {
		StringBuilder sb = new StringBuilder();
		try {
			writeJSONString(list, sb);
		} catch (IOException e) {
			// Can not append on a string builder
		}
		return sb.toString();
	}

	/**
	 * Encode a list into JSON text and write it to out. If this list is also a
	 * JSONStreamAware or a JSONAware, JSONStreamAware and JSONAware specific
	 * behaviours will be ignored at this top level.
	 * 
	 * @see net.minidev.json.JSONValue#writeJSONString(Object, Appendable)
	 */
	public static void writeJSONString(List list, Appendable out) throws IOException {
		if (list == null) {
			out.append("null");
			return;
		}

		boolean first = true;
		out.append('[');
		for (Object value : list) {
			if (first)
				first = false;
			else
				out.append(',');
			if (value == null)
				out.append("null");
			else
				JSONValue.writeJSONString(value, out);
		}
		out.append(']');
	}

	public void merge(Object o2) {
		JSONObject.merge(this, o2);
	}

	/**
	 * Explicitely Serialize Object as JSon String
	 */
	public String toJSONString() {
		return toJSONString(this);
	}

	/**
	 * Override natif toStirng()
	 */
	public String toString() {
		return toJSONString();
	}

	public void writeJSONString(Appendable out) throws IOException {
		writeJSONString(this, out);
	}
}