Creating a nested JSON object

15,520

Solution 1

'friends' is a JSONArray, each of its items is a JSONObject. Just use put with a JSONObject or JSONArray as value. For arrays, you will have to specify the index as well.

Solution 2

There is a function in JSONObject

put(String string, Object value)

that takes in a JSONArray, of which you can make it an array of JSONObject's. I'd imagine your "friend" class could generate the JSONObject that is be put into the list.

Solution 3

Checkout these JSON encoding examples, so you can manage it easily through.

JSON Encoding

Solution 4

i am switching the subject, but insist you to use Gson as it maintain a all element in one class with runtime getter/setter

Solution 5

Use this Json jar file its automatically set and get the values according to tagnames(Ex:firstname,lastname etc) download and usage of jar file get from belo link

Android json jar file

Share:
15,520
Harsha M V
Author by

Harsha M V

I turn ideas into companies. Specifically, I like to solve big problems that can positively impact millions of people through software. I am currently focusing all of my time on my company, Skreem, where we are disrupting the ways marketers can leverage micro-influencers to tell the Brand’s stories to their audience. People do not buy goods and services. They buy relations, stories, and magic. Introducing technology with the power of human voice to maximize your brand communication. Follow me on Twitter: @harshamv You can contact me at -- harsha [at] skreem [dot] io

Updated on June 05, 2022

Comments

  • Harsha M V
    Harsha M V almost 2 years

    I am trying to create a complex nested object like this:

    {
       "user":{
          "type":"facebook",
          "first_name":"harsha",
          "last_name":"mv",
          "gender":"male"
       },
       "friends":[
          {
             "id":"23",
             "name":"Vachana"
          },
          {
             "id":"23",
             "name":"Jyosna"
          },
          {
             "id":"23",
             "name":"Avinash"
          }
       ]
    }
    

    Android Java code:

        JSONObject user = new JSONObject();
        try {
            user.put("first_name", "harsha");
            user.put("last_name", "mv");
            user.put("gender", "mail");
    
            System.out.println(user);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
    

    I want to nest the other objects as shown above. Can someone tell me how I can do it? What function or format do I need to use?