简体   繁体   中英

Reading json from java application with python

I've been working on one project with my colleague. We have a python api, jquery web interface + java android interface. Basically, web&android should send data in json format and my api should read and process it. Python has no troubles with reading variables from post request from jquery via cgi. Here's snippet (without headers and stuff) that works just OK:

import cgi
storage = cgi.FieldStorage()
print(storage)

Return value is (as expected) something like:

FieldStorage(None, None, [MiniFieldStorage('command', 'xy'), MiniFieldStorage('extra', '168')])

With this, I can easily get value of command by calling

storage["command"].value

Unfortunately, when sending the same request from java, I don't get expected result. Here is a snippet we use at the moment.

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(LOGIN_URL);
JSONObject json = null;
try {
    json = new JSONObject("{\"command\":\"xy\",\"extra\":\"168\"}");

    se = new StringEntity(json.toString(), "UTF-8"); 
    se.setContentType("application/json; charset=UTF-8");

    httppost.setEntity(se);
    httppost.setHeader("Content-type", "application/json");
    HttpResponse response = httpclient.execute(httppost);

    BufferedReader reader = new BufferedReader(
            new InputStreamReader( response.getEntity().getContent(), "UTF-8") 
    );
    String jsonString = null;

    while((jsonString=reader.readLine())!=null){ Log.i("response",jsonString); }
    return null;
} 
catch (ClientProtocolException e) { e.printStackTrace();}  
catch (IOException e) { e.printStackTrace();} 
catch (JSONException e) { e.printStackTrace();}

When reading this request (print(storage)) in python, I get

FieldStorage(None, None, '{"command":"xy","extra":"168"}')

You can notice that altough I received the string, it's not an MiniFieldStorage instance and I can not read it.

storage.list

returns None. Also, I can not iterate over storage (TypeError, "not indexable")

We have been trying to solve this for hours and we are still not sure, where is the problem - whether its python/cgi or java (but I have a strong feeling that we have wrong java code since neither of us is a real java coder)

Note for non-python coders: I believe problem is that java sends a string instead of json object, but I may be also wrong - I dont have much experience with python.cgi

You don't show how you're posting your data from the "web" version, but it doesn't look as if you are posting JSON there: you're just sending normal form data, with the fields "command" and "extra".

But the Java version is sending JSON (your point about "sending a string" is irrelevant: strings are the way JSON data is transferred).

So, since you're not sending form-encoded data, cgi.FieldStorage is irrelevant and you should just read the raw data from sys.stdin , then decode it:

import sys
data = sys.stdin.read()
params = json.loads(data)

I hope this code is helpful.Reply me in case of any questions, will make this out for you. This code will use a api json-simple-1.1.1.jar which is for parsing jason. Download that from below link.

http://code.google.com/p/json-simple/downloads/detail?name=json-simple-1.1.1.jar&can=2&q=

This is a simple java demo that is parsing the same string you had given in your question , just use this logic in your java controller or any where in java class it will work.

package in.hrst;

import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

class JsonDecodeDemo 
{
   public static void main(String[] args) 
   {
       String s = "[{\"command\":\"xy\",\"extra\":\"168\"}]";
       decodeJson(s);
   }

   private static void decodeJson(String s) {

       JSONParser parser = new JSONParser();

       try {
           Object obj = parser.parse(s);
           JSONArray array = (JSONArray) obj;
           System.out.println("The 2nd element of array");
           System.out.println(array.get(0));
           System.out.println();

       } catch (ParseException pe) {
           System.out.println("position: " + pe.getPosition());
           System.out.println(pe);
       }
   }
}

The output in console of this program is :


Data in Json : {"extra":"168","command":"xy"}


enjoy programing dear

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