Json object from database in java

前端 未结 4 710
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 14:53

Can anyone help me how to create a JSON Object from the database?

This is what the JSON output should look like:

{“devicelist”:{
    “de         


        
4条回答
  •  轮回少年
    2021-02-04 15:04

    If you have a Device objects, json-lib can serialize the object using get() methods as JSON.

    import java.util.*;
    import net.sf.json.*;
    
    public class JsonEncode {
        public static void main(String[] args) throws Exception {
            Device d1 = new Device("01", "CAM", "LivingRoom");
            Device d2 = new Device("15", "CAM", "Kitchen");
    
            List devices = new ArrayList(Arrays.asList(d1, d2));
    
            JSONArray serializedDevices = JSONArray.fromObject(devices);
            JSONObject jsonDevices = new JSONObject();
            jsonDevices.put("devices", serializedDevices);
    
            JSONObject json = new JSONObject();
            json.put("deviceList", jsonDevices);
            System.out.println(json);
        }
    
        public static class Device {
            Device(String id, String type, String name) {
                this.id = id;
                this.type = type;
                this.name = name;
            }
            private String id;
            public String getId() { return id; }
            private String type;
            public String getType() { return type; }
            private String name;
            public String getName() { return name; }
        }
    }
    

    Saved as: JsonEncode.java

    Compiled with:

    javac -cp json-lib-2.4-jdk15.jar JsonEncode.java
    

    Executed with (Note: classpath has DOS separator):

    java -cp .;json-lib-2.4-jdk15.jar;commons-lang-2.6.jar;commons-logging-1.1.1.jar;commons-collections-3.2.1.jar;ezmorph-1.0.6.jar;commons-beanutils-1.8.0.jar JsonEncode
    

    Dependencies:

    • json-lib-2.4-jdk15.jar
    • commons-lang-2.6.jar
    • commons-logging-1.1.1.jar
    • commons-collections-3.2.1.jar
    • commons-beanutils-1.8.0.jar
    • ezmorph-1.0.6.jar

提交回复
热议问题