簡體   English   中英

JSON:從python到Java的序列化

[英]JSON : serialization from python to Java

我有一個可獲取json數據的python搜尋器,以及使用此數據的java程序。 我的方法是將json數據序列化為文件。 它在python中表示為字典,而我做到了:

mails_file.write(str(email)+'\n')

這將產生如下結果:

{u'from': u'Brian Yablonski <brian@jeb.org>', u'dateCentral': u'1999-01-05T07:33:06-06:00', u'to': u'"\'jeb@jeb.org\'" <jeb@jeb.org>', u'date': u'Tue, 5 Jan 1999 08:33:06 -0500', u'message': u"Missed the deadline, but I would have said the speech is a first step \ntoward restoring the rightful place of communities and families as the \nfirst source of ideas and solutions to our society's problems and to show \nthat government can work not as a master of, but a partner with, these \ninstitutions.\n\n-----Original Message-----\nFrom:\tJeb Bush [SMTP:jeb@jeb.org]\nSent:\tMonday, January 04, 1999 3:44 PM\nTo:\tYablonski Brian\nSubject:\tFW: Speech\n\nHow would you describe the speech for Mark?\n\n-----Original Message-----\nFrom:\tMark Silva [mailto:bureau@tdo.infi.net]\nSent:\tMonday, January 04, 1999 3:14 PM\nTo:\tJeb@jeb.org\nSubject:\tSpeech\n\nHave a quick thematic description for me about what you hope to accomplish\nwith tomorrow's inaugural address? (If you see this note before 6:30). If\nnot, thanks anyway and I wish you well Tuesday.", u'id': u'19990105-01BE3886.0851BC20.brian@jeb.org', u'subject': u'RE: Speech'}

然后我想做一些python-java格式的調整,例如:

line = line.replace('u"', '"')
line = line.replace("u'", '"')
line = line.replace("'", '"')

最后使用以下命令在Java中加載JSON對象:

JSONObject lineJson = new JSONObject(line);

由於python可互換使用"' chars,因此這種方法無法在我的95%的對象上使用。我如何克服這個問題並編寫一個實際可用的格式轉換函數?

您需要使用json模塊或等效模塊:

import json
# ...
json.dump(email, mails_file)

從有關json.dump的文檔中:

使用此轉換表將 obj作為JSON格式的流序列化為fp(支持.write() 的類似文件的對象 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM