简体   繁体   中英

Adding class object with multiple Arrylists

hi i am trying to add the class object with arrylists and need to display it in json format i used gson library for json format and iam tring to bind the java object into jsonformat has below

" {"type": "record","name": "Doc","doc": "adoc","fields": [{"name": "id","type": "string"}, {"name": "user_friends_count","type": ["int", "null"]}]"

and these the following classes and main method

public class RootFields {
public String type;
public String name;
public String doc;

}

public class Fields {
public String name;
public String type;

}

and this is my main method

public class JavaToJson{


    public static void main(String[] args) {
        // TODO Auto-generated method stub      
RootFields root = new RootFields();
List<Fields> F2 = new ArrayList<Fields>();
Fields F1 = new Fields();
Fields Fields1 = new Fields();
Fields Fields2 = new Fields();
root.type = "record";
root.name = "Doc";
root.doc = "adoc";
F1.name = "id";
F1.type = "string";
Fields1.name = "user_friends_count";
Fields1.type = "int";
Fields2.name = "user_location";
Fields2.type = "int";
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();

root.F2.add(F1);
System.out.println(gson.toJson(root));

    }

}

it shows me compile error F2 cannot be resolved or is not a field at F2 in "root.F2.add(F1)" where am i going wrong please help out thanks in advance.

You have not declared F2 as a field in RootFields . Though from what I understand, you should use either a List or an array, not several fields for each instance of Fields .

class RootFields {
    public String type;
    public String name;
    public String doc;
    List <Fields> filelds = new ArrayList<>();
}

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