简体   繁体   English

将不同类型的对象的JSON转换为Java List对象

[英]Convert a JSON of different type of objects into java List object

I have a JSON object stored in db in the form of string. 我有一个以字符串形式存储在db中的JSON对象。 I am using it to create dynamic form in the UI. 我正在使用它在UI中创建动态表单。 Now the problem is I want to change some values in it based on other changes happening on the application. 现在的问题是,我想根据应用程序上发生的其他更改来更改其中的某些值。 So suppose I updated label for the field, then I have to get this JSON and change that here. 因此,假设我更新了该字段的标签,那么我必须获取此JSON并在此处进行更改。 This would be easy If I have stored same type of objects in this json, but my JSON is like follows: 如果我在此json中存储了相同类型的对象,这将很容易,但是我的JSON如下所示:

[{
    "name": "someName",
    "xtype": "keyvaluecombo",
    "fieldLabel": "Some Title",
    "refType": "YES_NO",
    "multiSelect": false,
    "helpText": ""
  },
  {
    "name": "someName2",
    "xtype": "keyvaluecombo",
    "fieldLabel": "Some Title2",
    "refType": "YES_NO",
    "multiSelect": false,
    "helpText": ""
  },
  {
    "xtype": "datefield",
    "fieldLabel": "Joining Date",
    "name": "joiningDate",
    "submitFormat": "Y-m-d"
  },
  {
    "xtype": "userselectioncombo",
    "fieldLabel": "Selection",
    "name": "selections",
    "filterBy": {
      "functions": [
        "select"
      ]
    }
  }]

Now this is stored as String in db, what is efficient way of changing fieldLabel based on name. 现在,将其作为String存储在db中,这是根据名称更改fieldLabel的有效方法。 I could have tried working on it as string only and use regular expression, but that didn't feel right. 我本可以尝试仅将其作为字符串并使用正则表达式来处理,但这感觉不对。

You should write a bean class, which should be mapping to you Json object like, 您应该编写一个bean类,该类应该映射到您的Json对象,例如,

public class abc {

    private String name;
    private String xtype;
    private String fieldLabel;
    ........
}

Then you should use 那你应该用

import java.lang.reflect.Type;

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();

Type type = new TypeToken<List<abc>>() {
            }.getType();

List<abc> abcList = gson.fromJson(confTemplate,
                    type); // confTemplate is your Json object you get from DB

this will get the list of beans. 

for (abc abcData : abcList ) {
 // you can do your stuff
}

First of all the best way, changing your database design with a new one that suits your model. 首先,最好的方法是,使用适合您的模型的新方法来更改数据库设计。 Not keeping json in your database as a column. 不将json作为列保留在数据库中。 But if you can't do that, because sometimes it's impossible to change old db designs you can trace the following way. 但是,如果您不能这样做,因为有时无法更改旧的数据库设计,则可以跟踪以下方式。

And of course you should read your json from db before start and save it again after the below process. 当然,您应该在开始之前从db中读取json,并在以下过程之后再次保存它。

  1. Create a custom object that suits your model. 创建一个适合您的模型的自定义对象。

     public class MyObject{ private String name; private String fieldLabel; public String getFieldLabel(){ return fieldLabel; } public void setFieldLabel( String fieldLabel ){ this.fieldLabel = fieldLabel; } public String getName(){ return name; } public void setName( String name ){ this.name = name; } // bla bla other fields 
  2. Convert your json into your object, and vice versa see the code example below: 将您的json转换为对象,反之亦然,请参见下面的代码示例:

 public static void main( String[] args ){
        Gson gson = new Gson();
        String yourJson = "[{'name':'someName','xtype':'keyvaluecombo','fieldLabel':'Some Title','refType':'YES_NO','multiSelect':false,'helpText':''},{'name':'someName2','xtype':'keyvaluecombo','fieldLabel':'Some Title2','refType':'YES_NO','multiSelect':false,'helpText':''},{'xtype':'datefield','fieldLabel':'Joining Date','name':'joiningDate','submitFormat':'Y-m-d'},{'xtype':'userselectioncombo','fieldLabel':'Selection','name':'selections','filterBy':{'functions':['select']}}]";

        // changing single quotes with double ones.
        yourJson = yourJson.replaceAll( "'", "\"" );

        JsonArray jsonArray = new JsonParser().parse( yourJson ).getAsJsonArray();

        List<MyObject> result = new ArrayList<MyObject>();

        for( JsonElement jsonElement : jsonArray ){
            MyObject myObject = gson.fromJson( jsonElement, MyObject.class );

            // change fields as you wish
            if( myObject.getName().equals( "someName" ) ){
                myObject.setFieldLabel( "TEST" );
            }

            // add it to another list
            result.add( myObject );
        }

        // convert into another json again..
        System.out.println( gson.toJson( result ) );

    }

Easy to realize that Object in your list have attributes below: 容易意识到列表中的对象具有以下属性:

"name"
"xtype"
"fieldLabel"
"refType"
"multiSelect"
"helpText"
"submitFormat"
"filterBy"

So you can create an Object which has over attributes. 因此,您可以创建一个具有over属性的Object。 Using ObjectMapper for deserialize the list: 使用ObjectMapper反序列化列表:

ObjectMapper mapper = new ObjectMapper();
mapper.readValue(json, new TypeReference<ArrayList<T>>() {})

After have a list object you can loop for change any attribute or change attribute of an specific item you want. 在拥有列表对象之后,您可以循环更改所需的任何属性或更改特定项目的属性。

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

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