2

I am trying to have this exact JSON syntax but can't get to it:

{
    "sun":"yellow",
    "vegetables":[{
        "apple":"red",
        "banana":"yellow",
        "melon":"orange"
    }]
}

The closest I can get is:

{
    "sun":"yellow",
    "vegetables":["{
        "apple":"red",
        "banana":"yellow",
        "melon":"orange"
    "]}
}

This is what I am doing:

JSONObject json = new JSONObject();
json.put("sun","yellow");

ArrayList<HashMap<String,Object>> test = new ArrayList<HashMap<String,Object>>();
HashMap<String,Object> params = new HashMap<String, Object>();
params.put("apple","red");
params.put("banana","yellow");
params.put("melon","orange");

test.add(params);
json.put("fruits",test);

I can't figure it out, am I missing something?

1
  • 2
    "The closest I can get is:" version isn't even valid JSON! Also, you put in "fruits" so how does it come out "vegetables"? Whatever JSON parser you are using is awesome ;) Please run your application again and provide us with the real output rather than what you typed out! ;) Commented Jun 14, 2012 at 22:59

2 Answers 2

6

It should be like this -

JSONObject json = new JSONObject();
json.put("sun","yellow");

JSONArray veg = new JSONArray();
JSONObject vegData = new JSONObject();
vegData.put("apple","red");
vegData.put("banana","yellow");
vegData.put("melon","orange");

veg.put(vegData);   

json.put("vegetables",veg);

I am using Jettison. You can find details here.

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

1 Comment

Looks like you put your answer just a bit ahead of me.
0

Why not do nesting? Some examples here

JSONObject outer = new JSONObject();
JSONObject inner = new JSONObject();
JSONArray  array = new JSONArray();

outer.put("sun", "yellow");
array.put("apple", "red");
array.put("bannanna", "yellow");
array.put("melon", "orange");

inner.put(array);

outer.put("Vegtables":inner);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.