简体   繁体   中英

Writing JSONObject into a file

I'm using Play framework. I have a JSONObject which has a structure like the below (As in console it printed)

{
    "rows_map":{
        "220":["mahesh",
            "outfit:bmtech,app:salesreport,uuname,ffname,llname",
            "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5",
            null
        ],
"221":["mahesh",
            "outfit:bmtech,app:salesreport,uuname,ffname,llname",
            "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5",
            null
        ],
"222":["mahesh",
            "outfit:bmtech,app:salesreport,uuname,ffname,llname",
            "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5",
            null
        ],
"223":["mahesh",
            "outfit:bmtech,app:salesreport,uuname,ffname,llname",
            "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.5",
            null
        ]
},
    "columns_map":["Sender",
        "Message Received",
        "Device",
        "Time"
    ]
}

I want to write this JSONObject to a file. Here is the code

String path = "/var/www/html/Prj/public/CacheLayer/Incoming_Cache/CacheFileMgr.cache";

            ObjectOutputStream outputStream = null;
        try{
            outputStream = new ObjectOutputStream(new FileOutputStream(path));
            System.out.println("Start Writings");
                outputStream.writeObject(object);
                outputStream.flush();
                    outputStream.close();
          }catch (Exception e){
          System.err.println("Error: " + e);
          }

The above doesn't successfully writes to the file. Serialization error occurs.

Call toString on the JSONObject, and then serialize the string. JSONObject itself is not serializable.

String jsonString = jsonObject.toString();

JSON是序列化,它不实现可序列化,只需将其转换为字符串并将字符串保存在文件中(作为文本)。

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