简体   繁体   中英

JSON-encode an array of objects and arrays in Java for PHP

I've read a lot of answers about it, but sometimes they were arrays and some others were objects, here there are both together.

I have more variables of the same object stored in an array. Now i want to convert all of these to a string, so that i can send by HTTP POST request to the server and then PHP must be able to read them with JSON decode.

So that's the code Java in my Android app:

Object Class

class DataMisurati {
    float valori[]=new float[3];
    long tempo;
    DataMisurati() {  }
    DataMisurati(float[] values, long temp) { 
        this.valori[0] = values[0]; 
        this.valori[1] = values[1]; 
        this.valori[2] = values[2]; 
        this.tempo=temp;
    }

  }

And here some of the main code:

DataMisurati[] daticompleti;

//now i fill the array daticompleti

//here must be the code to Json the array of objects and then convert it to string

Then there must be the HTTP post with sending the string.

Would definitely agree with Vinnie that GSON is the way to go. Personally I'd suggest you skip the clever object binding stuff and look at the JSONWriter class instead. This is a lot quicker than the Gson.toJson() method (it doesn't do refection magic behind the scenes), uses less memory and scales better. The downside is you need to write a bit more code to encode your JSON, but I think that's a worthy trade-off when working on a constrained mobile platform.

Using JSONWriter also means you only need to import the GSON stream package into your app (14kb) rather than the full GSON package (515kb).

I believe the GSON stream package is essentially what Google have bundled into the latest versions of Android Framework.

I found Gson to be the easiest to work with custom objects. First download the Gson jar from here: http://code.google.com/p/google-gson/downloads/list

Then, import the jar into your project, this is done slightly differently based on the IDE you're using. Once you have the jar into your project, do an import statement at the top where all the other import statements are:

import com.google.gson.Gson;

Then go from object to string like this:

Gson gson = new Gson();
String jsonString = gson.toJson(daticompleti);

Then, in your http connection you want to set the request entity like this:

request.setEntity(new ByteArrayEntity(jsonString.getBytes("UTF8")));

or however you're doing the connection stuff. The important thing is to use the getBytes because post bodies use raw data.

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