Collector method to parse a JSON array into a Collection JsonArray
authorJaroslav Tulach <jtulach@netbeans.org>
Tue, 22 Jul 2014 18:29:06 +0200
branchJsonArray
changeset 747df2a61ad64e2
parent 746 5a1cc4708c34
child 748 38650a8eeec7
Collector method to parse a JSON array into a Collection
json-tck/src/main/java/net/java/html/json/tests/ConvertTypesTest.java
json/src/main/java/net/java/html/json/Models.java
json/src/main/java/org/netbeans/html/json/impl/JSON.java
src/main/javadoc/overview.html
     1.1 --- a/json-tck/src/main/java/net/java/html/json/tests/ConvertTypesTest.java	Tue Jul 22 18:06:57 2014 +0200
     1.2 +++ b/json-tck/src/main/java/net/java/html/json/tests/ConvertTypesTest.java	Tue Jul 22 18:29:06 2014 +0200
     1.3 @@ -46,7 +46,9 @@
     1.4  import java.io.EOFException;
     1.5  import java.io.InputStream;
     1.6  import java.io.UnsupportedEncodingException;
     1.7 +import java.util.ArrayList;
     1.8  import java.util.HashMap;
     1.9 +import java.util.List;
    1.10  import java.util.Map;
    1.11  import net.java.html.BrwsrCtx;
    1.12  import net.java.html.json.Models;
    1.13 @@ -57,22 +59,31 @@
    1.14   * @author Jaroslav Tulach <jtulach@netbeans.org>
    1.15   */
    1.16  public final class ConvertTypesTest {
    1.17 -    private static InputStream createIS(boolean includeSex, boolean includeAddress, boolean array) 
    1.18 +    private static InputStream createIS(boolean includeSex, boolean includeAddress, int array) 
    1.19      throws UnsupportedEncodingException {
    1.20          StringBuilder sb = new StringBuilder();
    1.21 -        if (array) {
    1.22 +        int repeat;
    1.23 +        if (array != -1) {
    1.24              sb.append("[\n");
    1.25 +            repeat = array;
    1.26 +        } else {
    1.27 +            repeat = 1;
    1.28          }
    1.29 -        sb.append("{ \"firstName\" : \"son\",\n");
    1.30 -        sb.append("  \"lastName\" : \"dj\" \n");
    1.31 -        if (includeSex) {
    1.32 -            sb.append(",  \"sex\" : \"MALE\" \n");
    1.33 +        for (int i = 0; i < repeat; i++) {
    1.34 +            sb.append("{ \"firstName\" : \"son\",\n");
    1.35 +            sb.append("  \"lastName\" : \"dj\" \n");
    1.36 +            if (includeSex) {
    1.37 +                sb.append(",  \"sex\" : \"MALE\" \n");
    1.38 +            }
    1.39 +            if (includeAddress) {
    1.40 +                sb.append(",  \"address\" : { \"street\" : \"Schnirchova\" } \n");
    1.41 +            }
    1.42 +            sb.append("}\n");
    1.43 +            if (i < array - 1) {
    1.44 +                sb.append(",");
    1.45 +            }
    1.46          }
    1.47 -        if (includeAddress) {
    1.48 -            sb.append(",  \"address\" : { \"street\" : \"Schnirchova\" } \n");
    1.49 -        }
    1.50 -        sb.append("}\n");
    1.51 -        if (array) {
    1.52 +        if (array != -1) {
    1.53              sb.append(']');
    1.54          }
    1.55          return new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
    1.56 @@ -102,7 +113,7 @@
    1.57      @KOTest
    1.58      public void parseConvertToPeople() throws Exception {
    1.59          final BrwsrCtx c = newContext();
    1.60 -        final InputStream o = createIS(true, false, false);
    1.61 +        final InputStream o = createIS(true, false, -1);
    1.62          
    1.63          Person p = Models.parse(c, Person.class, o);
    1.64          
    1.65 @@ -114,7 +125,7 @@
    1.66      @KOTest
    1.67      public void parseConvertToPeopleWithAddress() throws Exception {
    1.68          final BrwsrCtx c = newContext();
    1.69 -        final InputStream o = createIS(true, true, false);
    1.70 +        final InputStream o = createIS(true, true, -1);
    1.71          
    1.72          Person p = Models.parse(c, Person.class, o);
    1.73          
    1.74 @@ -126,6 +137,24 @@
    1.75      }
    1.76  
    1.77      @KOTest
    1.78 +    public void parseConvertToPeopleWithAddressIntoAnArray() throws Exception {
    1.79 +        final BrwsrCtx c = newContext();
    1.80 +        final InputStream o = createIS(true, true, -1);
    1.81 +        
    1.82 +        List<Person> arr = new ArrayList<Person>();
    1.83 +        Models.parse(c, Person.class, o, arr);
    1.84 +        
    1.85 +        assert arr.size() == 1 : "There is one item in " + arr;
    1.86 +        
    1.87 +        Person p = arr.get(0);
    1.88 +        assert "son".equals(p.getFirstName()) : "First name: " + p.getFirstName();
    1.89 +        assert "dj".equals(p.getLastName()) : "Last name: " + p.getLastName();
    1.90 +        assert Sex.MALE.equals(p.getSex()) : "Sex: " + p.getSex();
    1.91 +        assert p.getAddress() != null : "Some address provided";
    1.92 +        assert p.getAddress().getStreet().equals("Schnirchova") : "Is Schnirchova: " + p.getAddress();
    1.93 +    }
    1.94 +
    1.95 +    @KOTest
    1.96      public void testConvertToPeopleWithoutSex() throws Exception {
    1.97          final Object o = createJSON(false);
    1.98          
    1.99 @@ -139,7 +168,7 @@
   1.100      @KOTest
   1.101      public void parseConvertToPeopleWithoutSex() throws Exception {
   1.102          final BrwsrCtx c = newContext();
   1.103 -        final InputStream o = createIS(false, false, false);
   1.104 +        final InputStream o = createIS(false, false, -1);
   1.105          Person p = Models.parse(c, Person.class, o);
   1.106          
   1.107          assert "son".equals(p.getFirstName()) : "First name: " + p.getFirstName();
   1.108 @@ -150,7 +179,7 @@
   1.109      @KOTest
   1.110      public void parseConvertToPeopleWithAddressOnArray() throws Exception {
   1.111          final BrwsrCtx c = newContext();
   1.112 -        final InputStream o = createIS(true, true, true);
   1.113 +        final InputStream o = createIS(true, true, 1);
   1.114          
   1.115          Person p = Models.parse(c, Person.class, o);
   1.116          
   1.117 @@ -164,18 +193,46 @@
   1.118      @KOTest
   1.119      public void parseConvertToPeopleWithoutSexOnArray() throws Exception {
   1.120          final BrwsrCtx c = newContext();
   1.121 -        final InputStream o = createIS(false, false, true);
   1.122 +        final InputStream o = createIS(false, false, 1);
   1.123          Person p = Models.parse(c, Person.class, o);
   1.124          
   1.125          assert "son".equals(p.getFirstName()) : "First name: " + p.getFirstName();
   1.126          assert "dj".equals(p.getLastName()) : "Last name: " + p.getLastName();
   1.127          assert p.getSex() == null : "No sex: " + p.getSex();
   1.128      }
   1.129 +
   1.130 +    @KOTest
   1.131 +    public void parseFirstElementFromAbiggerArray() throws Exception {
   1.132 +        final BrwsrCtx c = newContext();
   1.133 +        final InputStream o = createIS(false, false, 5);
   1.134 +        Person p = Models.parse(c, Person.class, o);
   1.135 +        
   1.136 +        assert "son".equals(p.getFirstName()) : "First name: " + p.getFirstName();
   1.137 +        assert "dj".equals(p.getLastName()) : "Last name: " + p.getLastName();
   1.138 +        assert p.getSex() == null : "No sex: " + p.getSex();
   1.139 +    }
   1.140 +
   1.141 +    @KOTest
   1.142 +    public void parseAllElementFromAbiggerArray() throws Exception {
   1.143 +        final BrwsrCtx c = newContext();
   1.144 +        final InputStream o = createIS(false, false, 5);
   1.145 +        
   1.146 +        List<Person> res = new ArrayList<Person>();
   1.147 +        Models.parse(c, Person.class, o, res);
   1.148 +        
   1.149 +        assert res.size() == 5 : "Five elements found" + res;
   1.150 +        
   1.151 +        for (Person p : res) {
   1.152 +            assert "son".equals(p.getFirstName()) : "First name: " + p.getFirstName();
   1.153 +            assert "dj".equals(p.getLastName()) : "Last name: " + p.getLastName();
   1.154 +            assert p.getSex() == null : "No sex: " + p.getSex();
   1.155 +        }
   1.156 +    }
   1.157      
   1.158      @KOTest
   1.159      public void parseOnEmptyArray() throws Exception {
   1.160          final BrwsrCtx c = newContext();
   1.161 -        final InputStream o = new ByteArrayInputStream("[]".getBytes("UTF-8"));
   1.162 +        final InputStream o = createIS(false, false, 0);
   1.163          
   1.164          try {
   1.165              Models.parse(c, Person.class, o);
     2.1 --- a/json/src/main/java/net/java/html/json/Models.java	Tue Jul 22 18:06:57 2014 +0200
     2.2 +++ b/json/src/main/java/net/java/html/json/Models.java	Tue Jul 22 18:29:06 2014 +0200
     2.3 @@ -45,6 +45,7 @@
     2.4  import net.java.html.BrwsrCtx;
     2.5  import java.io.IOException;
     2.6  import java.io.InputStream;
     2.7 +import java.util.Collection;
     2.8  import org.netbeans.html.json.impl.JSON;
     2.9  
    2.10  /** Information about and 
    2.11 @@ -90,7 +91,29 @@
    2.12       * @since 0.2
    2.13       */
    2.14      public static <M> M parse(BrwsrCtx c, Class<M> model, InputStream is) throws IOException {
    2.15 -        return JSON.readStream(c, model, is);
    2.16 +        return JSON.readStream(c, model, is, null);
    2.17 +    }
    2.18 +    
    2.19 +    /** Generic method to parse stream, that can possibly contain array
    2.20 +     * of specified objects.
    2.21 +     * 
    2.22 +     * @param <M> the type of the individal JSON object
    2.23 +     * @param c context of the technology to use for reading 
    2.24 +     * @param model the model class generated by {@link Model} annotation
    2.25 +     * @param is input stream with data
    2.26 +     * @param collectTo collection to add the individual model instances to.
    2.27 +     *   If the stream contains an object, one instance will be added, if
    2.28 +     *   it contains an array, the number of array items will be added to
    2.29 +     *   the collection
    2.30 +     * @throws IOException thrown when an I/O problem appears
    2.31 +     * @since 0.8.3
    2.32 +     */
    2.33 +    public static <M> void parse(
    2.34 +        BrwsrCtx c, Class<M> model, 
    2.35 +        InputStream is, Collection<? super M> collectTo
    2.36 +    ) throws IOException {
    2.37 +        collectTo.getClass();
    2.38 +        JSON.readStream(c, model, is, collectTo);
    2.39      }
    2.40      
    2.41      /** Converts an existing, raw, JSON object into a {@link Model model class}.
     3.1 --- a/json/src/main/java/org/netbeans/html/json/impl/JSON.java	Tue Jul 22 18:06:57 2014 +0200
     3.2 +++ b/json/src/main/java/org/netbeans/html/json/impl/JSON.java	Tue Jul 22 18:29:06 2014 +0200
     3.3 @@ -405,18 +405,28 @@
     3.4          return PropertyBindingAccessor.clone(from, model, c);
     3.5      }
     3.6      
     3.7 -    public static <T> T readStream(BrwsrCtx c, Class<T> modelClazz, InputStream data) 
     3.8 +    public static <T> T readStream(BrwsrCtx c, Class<T> modelClazz, InputStream data, Collection<? super T> collectTo) 
     3.9      throws IOException {
    3.10          Transfer tr = findTransfer(c);
    3.11          Object rawJSON = tr.toJSON((InputStream)data);
    3.12          if (rawJSON instanceof Object[]) {
    3.13              final Object[] arr = (Object[])rawJSON;
    3.14 +            if (collectTo != null) {
    3.15 +                for (int i = 0; i < arr.length; i++) {
    3.16 +                    collectTo.add(read(c, modelClazz, arr[i]));
    3.17 +                }
    3.18 +                return null;
    3.19 +            }
    3.20              if (arr.length == 0) {
    3.21                  throw new EOFException("Recieved an empty array");
    3.22              }
    3.23              rawJSON = arr[0];
    3.24          }
    3.25 -        return read(c, modelClazz, rawJSON);
    3.26 +        T res = read(c, modelClazz, rawJSON);
    3.27 +        if (collectTo != null) {
    3.28 +            collectTo.add(res);
    3.29 +        }
    3.30 +        return res;
    3.31      }
    3.32      public static <T> T read(BrwsrCtx c, Class<T> modelClazz, Object data) {
    3.33          if (data == null) {
     4.1 --- a/src/main/javadoc/overview.html	Tue Jul 22 18:06:57 2014 +0200
     4.2 +++ b/src/main/javadoc/overview.html	Tue Jul 22 18:29:06 2014 +0200
     4.3 @@ -80,7 +80,10 @@
     4.4          <p>
     4.5              Setters or array properties on classes generated by {@link net.java.html.json.Model}
     4.6              annotation can be accessed from any thread. {@link org.apidesign.html.sound.spi.AudioEnvironment}
     4.7 -            can be registered into {@link net.java.html.BrwsrCtx}.
     4.8 +            can be registered into {@link net.java.html.BrwsrCtx}. There is
     4.9 +            a {@link net.java.html.json.Models#parse(net.java.html.BrwsrCtx, java.lang.Class, java.io.InputStream, java.util.Collection)  method}
    4.10 +            to parse a JSON array and convert it into 
    4.11 +            {@link net.java.html.json.Model model classes}.
    4.12          </p>
    4.13          
    4.14          <h3>What's New in Version 0.8.2?</h3>