I am working on a way to quickly build JSON strings in Java. To this end, I have created the following two files. Assuming that I do not need to parse JSON strings for Java, is this an efficient implementation? Furthermore, are there any cases where it would output an invalid JSON string?
JSONList.java:
public class JSONList
{
private ArrayList<JSON> items = null;
public JSONList()
{
this.items = new ArrayList<JSON>();
}
public JSONList add(JSON value)
{
if(value != null)
{
this.items.add(value);
}
else
{
throw new IllegalArgumentException("Value must be JSON, was " + (value == null ? "null" : value.getClass()));
}
return this;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
boolean first = true;
for(JSON j : this.items)
{
if(first)
{
first = false;
}
else
{
sb.append(",");
}
sb.append(j.toString());
}
return "[" + sb.toString() + "]";
}
JSON.java:
public class JSON
{
private HashMap<String, Object> parts = null;
public JSON()
{
this.parts = new HashMap<String, Object>();
}
public JSON add(String key, Object value)
{
if(value != null && (value instanceof String || value instanceof Boolean || value instanceof Integer || value instanceof Float || value instanceof JSONList))
{
this.parts.put(key, value);
}
else if(value == null)
{
this.parts.put(key, "null");
}
else
{
throw new IllegalArgumentException("Value must be either String, Boolean, Integer or Float, was " + (value == null ? "null" : value.getClass()));
}
return this;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
boolean first = true;
for(Entry<String, Object> entry : this.parts.entrySet())
{
Object v = entry.getValue();
if(first)
{
first = false;
}
else
{
sb.append(",");
}
if(v instanceof String)
{
sb.append("\"").append(entry.getKey()).append("\":\"").append(v).append("\"");
}
else if(v instanceof Boolean || v instanceof Integer || v instanceof Float)
{
sb.append("\"").append(entry.getKey()).append("\":").append(v);
}
else if(v instanceof JSONList)
{
sb.append("\"").append(entry.getKey()).append("\":").append(((JSONList) v).toString());
}
}
return "{" + sb.toString() + "}";
}
}
["GML", "XML"]
with this code? \$\endgroup\$