1

I'm trying to build a JSON string that looks like this:

{ "account": { "description": "desc2", "users": [ { "user": { "username": "Zogbi", "password": "password1", "firstName": "Tim", "lastName": "Smith", } } ] } }

What's coming out is this, though:

{ "account": { "users":[{ "middleName":"S","lastName":"Smith","username":"Zogbi","alias":"Gibbus","firstName":"Tim","password":"password1" } ] } }

So, two problems: 1. I need a "Description" after the "account" 2. I need a "user" object that's part of the "users" array.

Here is my code:

JSONObject account = new JSONObject();
JSONArray users = new JSONArray();
JSONObject user = new JSONObject();
JSONObject mainObj = new JSONObject();
account.put("users", users);
users.put("user");
user.put("username", "Zogbi");
user.put("password", "password1");
user.put("firstName", "Tim");
user.put("lastName", "Smith");
user.put("middleName", "S");
user.put("alias", "Gibbus");
mainObj.put("account", account);

Any help is appreciated!

3
  • You need one more object, one you might call "userElement", between "users" and "user". "userElement" goes into the "users" array, and the "user" object goes into the "userElement" object, using the key "user". Commented Sep 30, 2014 at 0:24
  • The other issue is simply a matter of putting a "description" entry (with string value) into the "account" object. Commented Sep 30, 2014 at 0:26
  • Thank you, both those suggestions worked. Commented Sep 30, 2014 at 16:10

2 Answers 2

1

get rid of the quotes when putting an object in the array.

You need another object, since users is an array of objects (lets call that userassoc), and those objects has a member "user" which is a user object. Something like this:

JSONObject account = new JSONObject();
JSONArray users = new JSONArray();
JSONObject userassoc = new JSONObject();
JSONObject user = new JSONObject();
JSONObject mainObj = new JSONObject();
account.put("users", users);
users.put(userassoc);
userassoc.put("user", user);
user.put("username", "Zogbi");
user.put("password", "password1");
user.put("firstName", "Tim");
user.put("lastName", "Smith");
user.put("middleName", "S");
user.put("alias", "Gibbus");
mainObj.put("account", account);    

Seems like an odd JSON structure. Did you get the assignment right?

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! That worked. Yes, that is the correct JSON definition. What is odd about it?
It is odd because there is a collection of "users", each element of that array is a (strange) object that has one member "user" which in turn contains the fields of a user. Thus you need this unusual "userAssoc" object which does not seem in my mind to have any purpose. Better data design is to put the user objects directly in the array called "users".
0

Building JSON manually is no better than building XML manually!

You wouldn't write a JPEG file by writing out the individual bytes any more than you should be writing individual object and array entries manually.

Use a well supported full featured JSON serializer/deserializer framework, my favorite is Jackson.

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.vertigrated.FormattedRuntimeException;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class Q26110375
{
    public static void main(final String[] args)
    {
        final User user = new User("Zogbi", "password1", "Tim", "S", "Smith", "Gibbus");
        final Account account = new Account("desc2", user);

        try
        {
            final ObjectMapper m = new ObjectMapper();
            m.enable(SerializationFeature.INDENT_OUTPUT);
            m.enable(SerializationFeature.WRAP_ROOT_VALUE);
            m.writeValue(System.out, account);
        }
        catch (final IOException e)
        {
            throw new FormattedRuntimeException(e, "Could not convert %s to Json because of %s", account.getClass(), e.getMessage());
        }
    }

    private static class User
    {
        @JsonProperty
        private final String username;
        @JsonProperty
        private final String password;
        @JsonProperty
        private final String firstName;
        @JsonProperty
        private final String middleName;
        @JsonProperty
        private final String lastName;
        @JsonProperty
        private final String alias;

        private User(@Nonnull final String username, @Nonnull final String password, @Nonnull final String firstName,
                     @Nonnull final String middleName, @Nonnull final String lastName, @Nonnull final String alias)
        {
            this.username = username;
            this.password = password;
            this.firstName = firstName;
            this.middleName = middleName;
            this.lastName = lastName;
            this.alias = alias;
        }
    }

    @JsonRootName("account")
    private static class Account
    {
        @JsonProperty
        private final String description;
        @JsonProperty
        private final List<User> users;

        private Account(@Nonnull final String description, @Nonnull final User... users)
        {
            this.description = description;
            this.users = Arrays.asList(users);
        }
    }
}

Painlessly generates the following:

{
  "account" : {
    "description" : "desc2",
    "users" : [ {
      "username" : "Zogbi",
      "password" : "password1",
      "firstName" : "Tim",
      "middleName" : "S",
      "lastName" : "Smith",
      "alias" : "Gibbus"
    } ]
  }
}

Complete project with all the dependencies is at my GitHub repository.

Code for FormattedRuntimeException.java

2 Comments

That Jackson code is 3 times what the "manual" code is, making it, right off the bat, 3 times as complicated. And likely takes 3 times as long to write. (And there's no way that JSON should ever be compared to XML.)
There is only 4 lines of Jackson code inside the try/catch block, the rest you need for actual non-trival Object Oriented development. Either way, this way wins when you have to add something to the structure, you just add it, you don't have to fiddle with intermediary holders and all that mess. Code is written to be read and maintained, manually building data structures like this is ridiculously error prone and tedious for non-trival scenarios.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.