Skip to content
Advertisement

Issue with Base64 encoding in Python and Decoding in Java

I have two packages running, one is written in python and the other in Java. The python package encodes a json(dictionary) object and sends it to the java package which decodes it into a specific POJO.

Let the json in python be:

{ "name": "John", "Age": 24, "Income": None }

The problem is that Java does not support None, it supports null, hence it is unable to parse the received json throwing error that “found None expected true, false, null, NaN”.

Base64 encoding of above json in python:

eyAibmFtZSI6ICJKb2huIiwgIkFnZSI6IDI0LCAiSW5jb21lIjogTm9uZX0=

Base64 encoding of above json in java:

eyAibmFtZSI6ICJKb2huIiwgIkFnZSI6IDI0LCAiSW5jb21lIjogbnVsbH0=

I need to parse the null value in Java as well and cannot simply drop it from the json. What can be the possible solutions to avoid this error?

Advertisement

Answer

The problem is that { "name": "John", "Age": 24, "Income": None } is not a valid JSON object because None is not a valid JSON value.

According to the JSON Grammar a value may be:

  • a string ("xy")
  • a number (12.345)
  • another object ({ "prop": "value" })
  • an array ([1,2,3])
  • true
  • false
  • null

If your json encoder produces the value None it is broken – maybe you should use the standard python encode:

import json
r = {"name": "John", "Age": 24, "Income": None}
enc = json.JSONEncoder()
print(enc.encode(r))

produces valid JSON that the Java JSON parser can parse:

{"name": "John", "Age": 24, "Income": null}

Is this data safe for transmission? I think so.

Using the following example:

import json
r = {"name": "Jöhn дое", "Age": 24, "Income": None}
enc = json.JSONEncoder()
print(enc.encode(r))

This is encoded into plain ASCII:

{"name": "Ju00f6hn u0434u043eu0435", "Age": 24, "Income": null}

And if you are not convinced that this is safe for transferring over the wire you can still use base64 encode the output of the JSONEncoder.encode() method.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement