001package org.javasimon.console.json; 002 003import org.javasimon.console.text.StringifierFactory; 004 005import java.io.IOException; 006import java.io.Writer; 007import java.util.ArrayList; 008import java.util.Collection; 009import java.util.List; 010 011/** 012 * JavaScript Array. 013 * 014 * @author gquintana 015 */ 016public class ArrayJS extends AnyJS { 017 018 /** Elements of the array. */ 019 private List<AnyJS> elements; 020 021 public ArrayJS() { 022 this.elements = new ArrayList<>(); 023 } 024 025 public ArrayJS(int size) { 026 this.elements = new ArrayList<>(size); 027 } 028 029 public ArrayJS(List<AnyJS> elements) { 030 this.elements = elements; 031 } 032 033 /** Gets elements of the array. */ 034 public List<AnyJS> getElements() { 035 return elements; 036 } 037 038 /** Adds an element in the array. */ 039 public void addElement(AnyJS element) { 040 elements.add(element); 041 } 042 043 @Override 044 public void write(Writer writer) throws IOException { 045 writer.write("["); 046 boolean first = true; 047 for (AnyJS element : elements) { 048 if (first) { 049 first = false; 050 } else { 051 writer.write(","); 052 } 053 element.write(writer); 054 } 055 writer.write("]"); 056 } 057 058 /** 059 * Create an JSON Array of JSON objects from a collection of Java Objects. 060 * 061 * @param objects Java Objects 062 * @param stringifierFactory JSON Stringifier converter 063 * @return Array of JSON Objects 064 */ 065 public static ArrayJS create(Collection<?> objects, StringifierFactory stringifierFactory) { 066 if (objects == null) { 067 return null; 068 } 069 ArrayJS arrayJS = new ArrayJS(objects.size()); 070 for (Object object : objects) { 071 arrayJS.addElement(ObjectJS.create(object, stringifierFactory)); 072 } 073 return arrayJS; 074 } 075 076 /** 077 * Create an JSON Array of JSON objects from a collection of Java Objects. 078 * 079 * @param objects Java Objects 080 * @param stringifierFactory JSON Stringifier converter 081 * @return Array of JSON Objects 082 */ 083 public static ArrayJS create(Object[] objects, StringifierFactory stringifierFactory) { 084 if (objects == null) { 085 return null; 086 } 087 ArrayJS arrayJS = new ArrayJS(objects.length); 088 for (Object object : objects) { 089 arrayJS.addElement(ObjectJS.create(object, stringifierFactory)); 090 } 091 return arrayJS; 092 } 093}