Wiki

Clone wiki

ToJsonString / Home

Introduction

A Java library for generating a JSON representation of a Java Object.

Getting Started

Include the following lines in your pom.xml file:

<dependency>
    <groupId>org.bitbucket.cowwoc</groupId>
    <artifactId>tojsonstring</artifactId>
    <version>1.3</version>
</dependency>

You can find the latest Javadoc at http://cowwoc.bitbucket.org/tojsonstring/javadoc/latest/

Example

Given:

public class Room
{
    private final int number = 3;
    private final Table table = new Table();
    private final Chair chair = new Chair();

    @Override
    public String toString()
    {
        return new ToJsonString().putAllFields(this).toString();
    }
}

public class Table
{
    private final int number = 1;

    @Override
    public String toString()
    {
        return new ToJsonString().setName(Table.class).putAllFields(this).toString();
    }
}

public class Chair
{
    private final int number = 2;

    @Override
    public String toString()
    {
        return new ToJsonString().putAllFields(this).toString();
    }
}

Room.toString() returns:

{
  "number": 3,
  "table": org.bitbucket.cowwoc.tojsonstring.Table
  {
    "number": 1
  },
  "chair": 
  {
    "number": 2
  }
}

In this example, Table.toString() outputs the class name. This isn't well-formed JSON but is useful for debugging purposes.

Related Projects

License

Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0

Updated