import java.io.*;
import javax.json.*;
import javax.json.stream.*;


/**
 * An encapsulation of an Address.
 * 
 * This is an example of "naive" serialization.
 * 
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0JSON
 */
public class Address
{
    private int    postalCode;
    private String city, state, streetAddress;

    /**
     * Construct an empty Person object.
     */
    private Address()
    {
    }
    
    /**
     * Populate the attributes of this Address object from
     * a JSON representation.
     * 
     * @param source  The JSON representation
     */
    public void fromJSON(JsonObject source)
    {
        streetAddress = source.getString("streetAddress");
        city = source.getString("city");
        state = source.getString("state");
        postalCode = source.getInt("postalCode");
    }

    /**
     * Construct an Address object from a JSON representation.
     * 
     * @param source  The JSON representation
     * @return        The Address object
     */
    public static Address parseAddress(JsonObject source)
    {
        Address result = new Address();
        result.fromJSON(source);
        return result;
    }

    /**
     * Create a JSON representation of this Address.
     * 
     * @return  A String containing the JSON representation
     */
    public String toJSON()
    {
        StringWriter out = new StringWriter();
        JsonGenerator g = Json.createGenerator(out); 
        toJSON(g, null);
        g.close();

        return out.toString();
    }

    /**
     * Create a JSON representation of this Person using the
     * given JsonGenerator.
     * 
     * @param g     The JsonGenerator to use
     * @param name  The name for the JsonObject (or null for none)
     */
    public void toJSON(JsonGenerator g, String name)
    {
        if (name == null) g.writeStartObject();
        else              g.writeStartObject(name);
        g.write("streetAddress", streetAddress);
        g.write("city", city);
        g.write("state", state);
        g.write("postalCode", postalCode);
        g.writeEnd();
    }
}
