Java Code Examples for org.boon.json.JsonFactory

The following examples show how to use org.boon.json.JsonFactory. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jdbc-cb   Source File: ClusterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBadInstance() throws Exception
{

    Cluster cluster = ((ProtocolImpl)((CBConnection) con).protocol).getCluster();

    String endpoint = "{\"cluster\":\"default\",\"name\":\"10.168.209.119\",\"queryEndpoint\":\"http://10.168.209.119:8093/query/service\"," +
            "\"adminEndpoint\":\"http://10.168.209.119:8093/admin\",\"options\":null}";

    ObjectMapper mapper = JsonFactory.create();
    Map <String,Object> instanceEndpoint = (Map)mapper.fromJson(endpoint);

    cluster.addEndPoint(instanceEndpoint);

    assertNotNull(con);
    Statement statement = con.createStatement();
    assertNotNull(statement);

    // there are only 4 endpoints we added 1 which is 5
    for (int i = 0; i++< 6;)
    {

        int inserted = statement.executeUpdate("INSERT INTO default  (KEY, VALUE) VALUES ( 'K" + i +"'," + i +")");
        assertEquals(1, inserted);
    }
}
 
Example 2
Source Project: boon   Source File: Bug199_2.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    Builder builder = new Builder();
    MetadataImpl metadataImpl = builder.getMetadata();

    JsonSerializerFactory jsonSerializerFactory=new JsonSerializerFactory().usePropertyOnly();
    ObjectMapper mapper = JsonFactory.create(null, jsonSerializerFactory);
    String json = mapper.writeValueAsString(metadataImpl);
    System.out.println("=============" + json);


    File file = new File("metadata.json");
    FileWriter writer = new FileWriter(file);
    mapper.toJson(metadataImpl, writer);
    writer.close();
    Path path = Paths.get(file.toString());
    InputStream inputStream = Files.newInputStream(path);


    MetadataImpl object = JsonFactory.create().readValue(inputStream,
            MetadataImpl.class);
    inputStream.close();

    System.out.println("after deserialization"
            + mapper.writeValueAsString(object));

}
 
Example 3
Source Project: jdbc-cb   Source File: CBArray.java    License: Apache License 2.0 5 votes vote down vote up
CBArray(List arrayList)
{
    if (arrayList == null )
    {
        array=null;
        jsonArray=null;
    }
    else
    {
        array = arrayList.toArray();
        jsonArray = JsonFactory.toJson(array);
    }
}
 
Example 4
Source Project: jdbc-cb   Source File: SqlJsonImplementation.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized void toJson()
{
    if (sqlJson == null )
    {
        sqlJson = JsonFactory.toJson(jsonObject);
    }

}
 
Example 5
Source Project: jdbc-cb   Source File: TestSQLJson.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void setSqlJson() throws Exception
{
    String json = "{\n" +
            "  \"emailAddress\": \"[email protected]\",\n" +
            "  \"type\": \"customer\",\n" +
            "  \"dateLastActive\": \"2014-05-06T15:52:14Z\",\n" +
            "  \"firstName\": \"Darrin\",\n" +
            "  \"phoneNumber\": \"497-854-2229 x000\",\n" +
            "  \"postalCode\": \"45603-9112\",\n" +
            "  \"lastName\": \"Ortiz\",\n" +
            "  \"ccInfo\": {\n" +
            "    \"cardNumber\": \"1234-2121-1221-1211\",\n" +
            "    \"cardType\": \"discover\",\n" +
            "    \"cardExpiry\": \"2012-11-12\"\n" +
            "  },\n" +
            "  \"dateAdded\": \"2013-06-10T15:52:14Z\",\n" +
            "  \"state\": \"IN\",\n" +
            "  \"customerId\": \"customer10\"\n" +
            "}";

    ObjectMapper mapper = JsonFactory.create();
    Map <String,Object> jsonObject = mapper.readValue(json, Map.class);

    String query = "insert into default (key,value) values (?,?)";

    SQLJSON sqljson = ((CBConnection)con).createSQLJSON();
    sqljson.setMap( jsonObject );
    try (PreparedStatement pstmt = con.prepareStatement(query))
    {
        pstmt.setString(1,"customer1");
        ((CBPreparedStatement)pstmt).setSQLJSON(2,sqljson);
        assertEquals(1,pstmt.executeUpdate());
    }
}
 
Example 6
Source Project: umlbot   Source File: UmlTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void outgoing() throws Exception {
	Map<String, String> map = new HashMap<>();
	map.put("token", TOKEN);
	map.put("trigger_word", "@startuml");
	String content = "hogehoge";
	map.put("text", "@startuml\n" + content + "\[email protected]");

	Request request = new MockUp<Request>() {
		@Mock
		Optional<String> form(String key) {
			return Optional.ofNullable(map.get(key));
		}
	}.getMockInstance();
	Response response = new MockUp<Response>() {
	}.getMockInstance();
	Object obj = this.target.outgoing(request, response);
	assertNotNull(obj);
	System.out.println(obj);
	Msg msg = JsonFactory.fromJson(obj.toString(), Msg.class);
	assertNotNull(msg.text);
	assertTrue(msg.text.startsWith(HOST));

	Transcoder t = Uml.transcoder();
	String enc = t.encode(content);
	assertTrue(msg.text.endsWith(enc));
}
 
Example 7
Source Project: boon   Source File: Bug199.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test() {

    JsonSerializerFactory factory = new JsonSerializerFactory();
    factory.usePropertyOnly();
    ObjectMapper mapper = JsonFactory.create(null, factory);

    User user = new User();
    EnumMap<Gender,User> map = new EnumMap<Gender, User>(Gender.class);
    map.put(Gender.FEMALE, user);

    puts(map);
    puts(mapper.writeValueAsString( map));
}
 
Example 8
Source Project: jdbc-cb   Source File: CBArray.java    License: Apache License 2.0 4 votes vote down vote up
CBArray(String typeName, Object[] array)
{
    this.array = array;
    baseType = typeName;
    jsonArray = JsonFactory.toJson(array);
}
 
Example 9
Source Project: jdbc-cb   Source File: Credentials.java    License: Apache License 2.0 4 votes vote down vote up
public String toString()
{
    return JsonFactory.toJson(credentials);
}
 
Example 10
Source Project: jdbc-cb   Source File: ProtocolImpl.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public Cluster handleClusterResponse(CloseableHttpResponse response) throws IOException
{
    int status = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();
    String string = EntityUtils.toString(entity);
    logger.trace ("Cluster response {}", string);
    ObjectMapper mapper = JsonFactory.create();

    // has to be an object here since we can get a 404 back which is a string
    Object jsonArray = mapper.fromJson(string);

    String message="";

    switch (status)
    {
        case 200:
            //noinspection unchecked
            rewriteURLs((List<Map>)jsonArray);
            return new Cluster((List)jsonArray, ssl);
        case 400:
            message = "Bad Request";
            break;
        case 401:
            message = "Unauthorized Request credentials are missing or invalid";
            break;
        case 403:
            message = "Forbidden Request: read only violation or client unauthorized to modify";
            break;
        case 404:
            message = "Not found: Check the URL";
            break;
        case 405:
            message = "Method not allowed: The REST method type in request is supported";
            break;
        case 409:
            message = "Conflict: attempt to create a keyspace or index that already exists";
            break;
        case 410:
            message = "Gone: The server is doing a graceful shutdown";
            break;
        case 500:
            message = "Internal server error: unforeseen problem processing the request";
            break;
        case 503:
            message = "Service Unavailable: there is an issue preventing the request from being serv serviced";
            break;
    }
    throw new ClientProtocolException(message +": " + status);

}
 
Example 11
Source Project: jdbc-cb   Source File: ProtocolImpl.java    License: Apache License 2.0 4 votes vote down vote up
public CouchResponse doQuery(String query, Map queryParameters) throws SQLException
{
    Instance endPoint = getNextEndpoint();

    // keep trying endpoints
    while(true)
    {

        try {
            String url = endPoint.getEndpointURL(ssl);

            logger.trace("Using endpoint {}", url);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");

            logger.trace("do query {}", httpPost.toString());
            addOptions(queryParameters);


            String jsonParameters = JsonFactory.toJson(queryParameters);
            StringEntity entity = new StringEntity(jsonParameters, ContentType.APPLICATION_JSON);


            httpPost.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(httpPost);

            return handleResponse(query, response);

        }
        catch (ConnectTimeoutException cte)
        {
            logger.trace(cte.getLocalizedMessage());

            // this one failed, lets move on
            invalidateEndpoint(endPoint);
            // get the next one
            endPoint = getNextEndpoint();
            if (endPoint == null) {
                throw new SQLException("All endpoints have failed, giving up");
            }


        } catch (Exception ex) {
            logger.error("Error executing query [{}] {}", query, ex.getMessage());
            throw new SQLException("Error executing update", ex);
        }
    }
}
 
Example 12
Source Project: jdbc-cb   Source File: ProtocolImpl.java    License: Apache License 2.0 4 votes vote down vote up
public int [] executeBatch() throws SQLException
{
    try
    {
        Instance instance = getNextEndpoint();
        String url = instance.getEndpointURL(ssl);

        HttpPost httpPost = new HttpPost( url );
        httpPost.setHeader("Accept", "application/json");

        Map <String,Object> parameters = new HashMap<String,Object>();
        addOptions(parameters);
        for (String query:batchStatements)
        {
            parameters.put(STATEMENT, query);
        }

        CloseableHttpResponse response = httpClient.execute(httpPost);
        int status = response.getStatusLine().getStatusCode();

        if ( status >= 200 && status < 300 )
        {
            HttpEntity entity = response.getEntity();
            ObjectMapper mapper = JsonFactory.create();
            @SuppressWarnings("unchecked") Map <String,Object> jsonObject = (Map)mapper.fromJson(EntityUtils.toString(entity));

            String statusString = (String)jsonObject.get("status");

            if (statusString.equals("errors"))
            {
                List errors= (List)jsonObject.get("errors");
                Map error = (Map)errors.get(0);
                throw new SQLException((String)error.get("msg"));
            }
            else if (statusString.equals("success"))
            {
                Map  metrics = (Map)jsonObject.get("metrics");
                if ( metrics.containsKey("mutationCount") )
                {
                    updateCount = (int)metrics.get("mutationCount");
                    return new int [0];
                }
                if ( metrics.containsKey("resultCount") )
                {
                   // TODO FIX ME resultSet = new CBResultSet(jsonObject);
                    return new int [0];
                }
            }
            else if (statusString.equals("running"))
            {
                return new int [0];
            }
            else if (statusString.equals("completed"))
            {
                return new int [0];
            }
            else if (statusString.equals("stopped"))
            {
                return new int [0];
            }
            else if (statusString.equals("timeout"))
            {
                return new int [0];
            }
            else if (statusString.equals("fatal"))
            {
                return new int [0];
            }

            else
            {
                //logger.error("Unexpected status string {} for query {}", statusString, query);
                throw new SQLException("Unexpected status: " + statusString);
            }
        }

        else
        {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
    }
    catch (Exception ex)
    {
        //logger.error ("Error executing update query {} {}", query, ex.getMessage());
        throw new SQLException("Error executing update",ex.getCause());
    }
    return new int [0];

}
 
Example 13
Source Project: jdbc-cb   Source File: PreparedStatementTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void schemaLessTest() throws Exception
{

    String name1 = "{\"name\":\"Travel Route1\", \"cities\": [ \"C1\", \"C2\", \"C3\" ],  " +
            "\"type\": \"route\" }";
    String name2 = "{\"name\":\"First Town\", \"type\": \"city\"}";
    String name3 = "{\"name\":\"Second Stop\", \"type\": \"city\"}";
    String name4 = "{\"name\":\"Destination\", \"type\": \"city\"}";

    try (PreparedStatement preparedStatement = con.prepareStatement("insert into default(key,value) values (?,?)"))
    {
        Map <String, String> jsonObject = (Map <String, String>)JsonFactory.fromJson(new StringReader(name1));
        preparedStatement.setString(1,"name");
        preparedStatement.setString(2, jsonObject.get("name"));

        assertEquals(1, preparedStatement.executeUpdate());

        jsonObject = (Map <String, String>)JsonFactory.fromJson(new StringReader(name2));
        preparedStatement.setString(1,"name1");
        preparedStatement.setString(2, jsonObject.get("name"));

        assertEquals(1, preparedStatement.executeUpdate());

        jsonObject = (Map <String, String>)JsonFactory.fromJson(new StringReader(name3));
        preparedStatement.setString(1,"name2");
        preparedStatement.setString(2, jsonObject.get("name"));

        assertEquals(1, preparedStatement.executeUpdate());

        jsonObject = (Map <String, String>)JsonFactory.fromJson(new StringReader(name4));
        preparedStatement.setString(1,"name3");
        preparedStatement.setString(2, jsonObject.get("name"));

        assertEquals(1, preparedStatement.executeUpdate());
    }
    /*
    try(Statement statement = con.createStatement())
    {
        ResultSet rs = statement.executeQuery("SELECT r.name as route_name, c as route_cities " +
                                                "FROM default r NEST travel c ON KEYS r.cities" +
                                                " WHERE r.name = \"Travel Route1\"");
        assertTrue(rs.next());
    }
    */

}
 
Example 14
Source Project: jdbc-cb   Source File: PreparedStatementTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testSetUserArray() throws Exception
{
    List arrayList = new ArrayList();
    arrayList.add(new TestUser("dave", "cramer", 54, true));
    arrayList.add(new TestUser("joe", "shmo", 15, false));
    arrayList.add(new TestUser("sue", "sandy", 30, true));

    Array array = con.createArrayOf("TestUser", arrayList.toArray());

    try(PreparedStatement preparedStatement = con.prepareStatement("insert into default(key,value) values (?,?)"))
    {
        preparedStatement.setString(1,"val1");
        preparedStatement.setArray(2, array);

        assertEquals(1, preparedStatement.executeUpdate());


        preparedStatement.setString(1,"val3");
        preparedStatement.setNull(2, Types.ARRAY, "array");

        assertEquals(1, preparedStatement.executeUpdate());

        try(Statement statement = con.createStatement())
        {
            try (ResultSet rs = statement.executeQuery("select * from default where meta(default).id='val1'"))
            {
                assertTrue(rs.next());
                List testArray = JsonFactory.fromJsonArray(((CBArray) rs.getArray("default")).getJsonArray(), TestUser.class);

                Assert.assertThat(arrayList,IsEqual.equalTo(testArray));
            }
            try (ResultSet rs = statement.executeQuery("select * from default where meta(default).id='val3'"))
            {
                assertTrue(rs.next());
                assertNull( rs.getArray("default"));
                assertTrue( rs.wasNull() );
            }
        }

    }
}
 
Example 15
Source Project: boon   Source File: Bug312.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void test() {

    MyClass myClass = new MyClass();
    final String json = JsonFactory.toJson(myClass);

    final MyClass myClass1 = JsonFactory.fromJson(json, MyClass.class);

    assertEquals("foo", myClass1.string);

    assertEquals(1, myClass1.integer);


    assertNull(myClass1.map);


}
 
Example 16
Source Project: boon   Source File: Bug312.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testWithMap() {

    MyClass myClass = new MyClass();
    myClass.map = new HashMap<>();
    myClass.map.put("foo", "bar");
    final String json = JsonFactory.toJson(myClass);

    final MyClass myClass1 = JsonFactory.fromJson(json, MyClass.class);

    assertEquals("foo", myClass1.string);

    assertEquals(1, myClass1.integer);


    assertEquals("bar", myClass1.map.get("foo"));


}
 
Example 17
Source Project: boon   Source File: Bug312.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testWithMapUsingFactory() {
    JsonParserFactory jsonParserFactory = new JsonParserFactory()
            .useFieldsFirst()
            .lax() //allow loose parsing of JSON like JSON Smart
            .setCharset( StandardCharsets.UTF_8 ) //Set the standard charset, defaults to UTF_8
            .setLazyChop( true ) //similar to chop but only does it after map.get
            ;

    JsonSerializerFactory jsonSerializerFactory = new JsonSerializerFactory()
            .useFieldsFirst() //one of these
                    //.addPropertySerializer(  )  customize property output
                    //.addTypeSerializer(  )      customize type output
            .useJsonFormatForDates() //use json dates
                    //.addFilter(  )   add a property filter to exclude properties
            .includeEmpty().includeNulls().includeDefaultValues() //override defaults
            .handleComplexBackReference() //uses identity map to track complex back reference and avoid them
            .setHandleSimpleBackReference( true ) //looks for simple back reference for parent
            .setCacheInstances( true ) //turns on caching for immutable objects
            ;

    final ObjectMapper objectMapper = JsonFactory.create(jsonParserFactory, jsonSerializerFactory);


    MyClass myClass = new MyClass();
    final String json = objectMapper.toJson(myClass);

    puts(json);

    final MyClass myClass1 = objectMapper.readValue(json, MyClass.class);


    assertEquals("foo", myClass1.string);

    assertEquals(1, myClass1.integer);


    assertNull(myClass1.map);


}
 
Example 18
Source Project: boon   Source File: Bug297.java    License: Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

            // create object
            MyObject myobject = new MyObject();
            // add a title and attributes
            myobject.setTitle("title with \" double qoutes");
            Map<String,Object> attributes = new HashMap<>();
            attributes.put("author", "author with \" double quotes");
            myobject.setAttrs(attributes);

            // create ObjectMapper
            ObjectMapper mapper = JsonFactory.create();

            // serialize myobject to json
            String myobjectJson = mapper.toJson(myobject);
            System.out.println(myobjectJson);
            // prints: {"title":"title with \" double qoutes","attrs":{"author":"author with \" double quotes"}}
            // parse myobjectJson to an object
            MyObject myobjectParsed = mapper.fromJson(myobjectJson, MyObject.class);

            final boolean equals = myobjectParsed.equals(myobject);

            System.out.println("equals " + equals + " " + myobjectParsed.title);

            System.out.println(myobjectParsed.title);

            System.out.println(myobjectParsed.getAttrs().get("author").getClass().getName());


            puts("\n", myobjectParsed, "\n", myobject);

            // serialize again my myobjectParsed to json
            myobjectJson = mapper.toJson(myobjectParsed);
            System.out.println(myobjectJson);
            // double quoted for attrs are not escaped
            // prints: {"title":"title with \" double qoutes","attrs":{"author":"author with " double quotes"}}


            MyObject myobjectParsed2 = mapper.fromJson(myobjectJson,MyObject.class);
            // Exception in thread "main" org.boon.json.JsonException: expecting current character to be ':' but got '}' with an int value of 125

        }
 
Example 19
Source Project: boon   Source File: BugReport165AndIssue169.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void test4() {
    Sample sample1 = new Sample();
    String json = JsonFactory.toJson(sample1);
    puts(json);
    puts (sample1);

    ok = json.contains("\"effectiveDate\"") || die();

    Sample sample2 = JsonFactory.fromJson(json, Sample.class);

    puts ("sample2", sample2);

    puts ("sample2", JsonFactory.toJson(sample2));

    ok = sample1.equals(sample2);

}
 
Example 20
Source Project: boon   Source File: Bug273.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public  void test() {
    A a = new JsonParserFactory().createUTF8DirectByteParser().parse(A.class, "{\"m\":{\"a\":\"b\"}}");
    System.out.println(JsonFactory.toJson(a));
}
 
Example 21
Source Project: boon   Source File: Bug287.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void serializingClassFieldCausesSegFault() {

    SomeClass someClassInstance = new SomeClass(Bug287.class);

    ObjectMapper mapper = JsonFactory.create();

    final String json = mapper.toJson(someClassInstance);

    puts(json);

    SomeClass someClassInstance2 = mapper.readValue("{\"clazz\":\"org.boon.bugs.Bug287\"} ", SomeClass.class);

    ok = someClassInstance2.clazz.getName().equals("org.boon.bugs.Bug287");

}
 
Example 22
Source Project: boon   Source File: HowToParseJSONInJava.java    License: Apache License 2.0 4 votes vote down vote up
public static void main(String... args) throws Exception{

        Player kevin = new Player("Kevin", "Cricket", 32, 221,
                new int[]{33, 66, 78, 21, 9, 200});

        final ObjectMapper mapper = JsonFactory.create();


        final File file = File.createTempFile("json", "exmaple.json");
        mapper.writeValue(file, kevin);



        Player somePlayer = mapper.readValue(file, Player.class);

        puts("They are equal", somePlayer.equals(kevin));


    }
 
Example 23
Source Project: boon   Source File: BugReport165AndIssue169.java    License: Apache License 2.0 3 votes vote down vote up
@Test
public void test2() {

    Employee employee = new Employee();

    ObjectMapper mapper = JsonFactory.create();

    String json = mapper.toJson(employee);

    puts(json);

    employee.name = "Rick Hightower";

    json = mapper.toJson(employee);

    puts(json);

    employee.birthDate = System.currentTimeMillis() - 60 * 1000 * 24 * 7 * 52 * 29;


    json = mapper.toJson(employee);

    puts(json);

    Employee newEmployee = mapper.fromJson(json, Employee.class);

    puts("New Employee", newEmployee.birthDate, newEmployee.name);


    ok = newEmployee.name.equals("Rick Hightower") && newEmployee.birthDate > 0 || die();

}
 
Example 24
Source Project: boon   Source File: Bug311.java    License: Apache License 2.0 3 votes vote down vote up
@Test
public  void test () {



    final String json = JsonFactory.toJson(new SimpleObject());

    final SimpleObject simpleObject = JsonFactory.fromJson(json, SimpleObject.class);

    assertEquals(Float.NEGATIVE_INFINITY, simpleObject.f1, 0.1);

    assertEquals(Float.NaN, simpleObject.f2, 0.1);

}
 
Example 25
Source Project: boon   Source File: Boon.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Helper method to quickly convert a Java object into JSON.
 * Facade into the JSON system.
 *
 * @param value Java object
 * @return JSON-ified Java object
 */
public static String toJson(Object value) {
    return JsonFactory.toJson(value);
}
 
Example 26
Source Project: boon   Source File: Boon.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Helper method to quickly convert JSON into a Java object.
 * Facade into the JSON system.
 *
 * @param value JSON content
 * @return Java object
 */
public static Object fromJson(String value) {
    return JsonFactory.fromJson(value);
}
 
Example 27
Source Project: boon   Source File: Boon.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Helper method to quickly convert JSON into a Java object.
 * Facade into the JSON system.
 *
 * @param value JSON content
 * @param clazz type you want to convert the JSON to
 * @return Java object
 */
public static <T> T fromJson(String value, Class<T> clazz) {
    return JsonFactory.fromJson(value, clazz);
}
 
Example 28
Source Project: boon   Source File: Boon.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * converts JSON into strongly typed list
 *
 * @param value value
 * @param clazz class
 * @param <T>   T
 * @return new list
 */
public static <T> List<T> fromJsonArray(String value, Class<T> clazz) {
    return JsonFactory.fromJsonArray(value, clazz);
}
 
Example 29
Source Project: boon   Source File: PartialDataTreeExample.java    License: Apache License 2.0 2 votes vote down vote up
public static void main (String... args) {
    File file = new File(".", "src/test/resources/teams.json");
    String path = file.getAbsolutePath().toString();
    puts ("PATH", path);
    puts ("CONTENTS of PATH", IO.read(path));

    /* Jackson style interface. */
    ObjectMapper mapper = JsonFactory.create();
    Object jsonObject = mapper.readValue(file, Object.class);
    puts ("JSON Object", jsonObject);


    /* Using Boon path. */
    puts ("teamInfo", atIndex(jsonObject, "teamInfo"));
    puts("Team Roster", atIndex(jsonObject, "teamInfo.teamRoster"));
    puts("Team Names", atIndex(jsonObject, "teamInfo.teamRoster.teamNames"));


    /* Using Boon style parser (fast). */
    JsonParserAndMapper boonMapper = new JsonParserFactory().create();
    jsonObject = boonMapper.parseFile(path);


    /* Using Boon path. */
    puts ("teamInfo", atIndex(jsonObject, "teamInfo"));
    puts("Team Roster", atIndex(jsonObject, "teamInfo.teamRoster"));
    puts("Team Names", atIndex(jsonObject, "teamInfo.teamRoster.teamNames"));



    /* Using Boon style (easy) 2 parser. */
    jsonObject = Boon.jsonResource(path);


    /* Using Boon path. */
    puts ("teamInfo", atIndex(jsonObject, "teamInfo"));
    puts("Team Roster", atIndex(jsonObject, "teamInfo.teamRoster"));
    puts("Team Names", atIndex(jsonObject, "teamInfo.teamRoster.teamNames"));

    //There is also a Groovy style and a GSON style.

    List<String> teamNames = (List<String>) atIndex(jsonObject, "teamInfo.teamRoster.teamNames");

    puts("Team Names", teamNames);

    Set<String> teamNameSet = set(teamNames);

    puts ("Converted to a set", teamNameSet);


    TeamInfo teamInfo = fromMap((Map<String, Object>) atIndex(jsonObject, "teamInfo"), TeamInfo.class);
    puts(teamInfo);


    TeamRoster teamRoster = fromMap((Map<String, Object>) atIndex(jsonObject, "teamInfo.teamRoster"), TeamRoster.class);
    puts(teamRoster);

}