Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 432
Arasu Avatar asked Sep 14 '11 13:09

Arasu


People also ask

How do you write JSON data to a file in Python?

Another way of writing JSON to a file is by using json.dump() method The JSON package has the “dump” function which directly writes the dictionary to a file in the form of JSON, without needing to convert it into an actual JSON object.

Can we convert JSON object to String?

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

How do I add files to a JSON file?

Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.


2 Answers

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

String jsonString = jsonObject.toString();
like image 199
Mike K. Avatar answered Oct 17 '22 17:10

Mike K.


JSON is the serialization, it doesn't implement serializable, just convert it to string and save the string in a file (as text).

like image 39
MByD Avatar answered Oct 17 '22 16:10

MByD