简体   繁体   中英

Logical solution for creating a JSON structure

I am not sure if it possible or not but I think it can be done using JSONArray.put method.
Heres my problem:

I have got two lists:

ArrayList<Students> nativeStudents;
ArrayList<transferStudents> transferStudents = nativeStudents.getTransferStudentsList();

The JSON that I generate with transferStudents list is right here: http://jsfiddle.net/QLh77/2/ using the following code:

  public static JSONObject getMyJSONObject( List<?> list )
    {
        JSONObject json = new JSONObject();
        JsonConfig config = new JsonConfig();
        config.addIgnoreFieldAnnotation( MyAppJsonIgnore.class );

        if( list.size() > 0 )
        {
            JSONArray array = JSONArray.fromObject( list, config );

            json.put( "students", array );
        }
        else
        {
            //Empty Array
            JSONArray array = new JSONArray();
            json.put( "students",
                      array );
        }

        return json;
    }

Now what I want to get is JSON data with following structure: http://jsfiddle.net/bsa3k/1/ (Notice the tempRollNumber field in both array elements).
I was thinking of doing: (The if condition here is used for a business logic)

if(transferStudents.getNewStudentDetails().getRollNumber() == nativeStudents.getNativeStudentDetails.getStudentId()){

     json.put("tempRollNumber", transferStudents.getNewStudentDetails().getRollNumber());

}

but this would add tempRollNumber outsite the array elements, I want this JSON element to be part of every entry of students array.

PS: I cant edit the transferStudents class in order to add tempRollNumber field.

Since no one has come up with anything better I'll turn my comments above into an answer.

The best way to handle this is to create an object model of your data and not create the JSON output yourself. Your app server or container can handle that for you.

Though you cannot change the objects you receive in the List you can extend the object's class to add your own fields. Those fields would then appear in the JSON when you marshall it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM