简体   繁体   English

用于创建JSON结构的逻辑解决方案

[英]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. 我不确定是否可以,但是我认为可以使用JSONArray.put方法完成。
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: 我使用transferStudents列表生成的JSON就在这里: http : //jsfiddle.net/QLh77/2/,使用以下代码:

  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). 现在,我要获取的是具有以下结构的JSON数据: http : //jsfiddle.net/bsa3k/1/ (请注意两个数组元素中的tempRollNumber字段)。
I was thinking of doing: (The if condition here is used for a business logic) 我正在考虑这样做:(此处的if条件用于业务逻辑)

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. 但这会在数组元素的外部添加tempRollNumber,我希望此JSON元素成为学生数组的每个条目的一部分。

PS: I cant edit the transferStudents class in order to add tempRollNumber field. PS:我不能编辑transferStudents类以添加tempRollNumber字段。

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. 解决此问题的最佳方法是创建数据的对象模型,而不是自己创建JSON输出。 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. 尽管您无法更改在List收到的对象,但是可以扩展对象的类以添加自己的字段。 Those fields would then appear in the JSON when you marshall it. 编组后,这些字段将出现在JSON中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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