简体   繁体   English

JSON:从python到Java的序列化

[英]JSON : serialization from python to Java

I have a python crawler that obtains json data and java program that uses this data. 我有一个可获取json数据的python搜寻器,以及使用此数据的java程序。 My approach was to serialize the json data into a file. 我的方法是将json数据序列化为文件。 It was represented in python as a dictionary and I did: 它在python中表示为字典,而我做到了:

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

which will yield a result such as: 这将产生如下结果:

{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'}

then I want to do some python-java format adjustments such as : 然后我想做一些python-java格式的调整,例如:

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

And finally load the JSON objects in java using: 最后使用以下命令在Java中加载JSON对象:

JSONObject lineJson = new JSONObject(line);

This approach fails on 95% of my objects, due python's interchangeable use of " & ' chars. How can I overcome this problem and write a format conversion function that will actually work? 由于python可互换使用"' chars,因此这种方法无法在我的95%的对象上使用。我如何克服这个问题并编写一个实际可用的格式转换函数?

You need to use the json module or an equivalent: 您需要使用json模块或等效模块:

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

From the documentation about json.dump : 从有关json.dump的文档中:

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object ) using this conversion table . 使用此转换表将 obj作为JSON格式的流序列化为fp(支持.write() 的类似文件的对象 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM