如何将对象序列化为JSON?

时间:2022-08-23 08:27:50

I need to serialize some objects to a JSON and send to a WebService. How can I do it using the org.json library? Or I'll have to use another one? Here is the class I need to serialize:

我需要将一些对象序列化为JSON并发送到WebService。我如何使用org。json库?或者我得再用一个?这是我需要序列化的类:

public class PontosUsuario {

    public int idUsuario;
    public String nomeUsuario;
    public String CPF;
    public String email;
    public String sigla;
    public String senha;
    public String instituicao;

    public ArrayList<Ponto> listaDePontos;


    public PontosUsuario()
    {
        //criando a lista
        listaDePontos = new ArrayList<Ponto>();
    }

}

I only put the variables and the constructor of the class but it also have the getters and setters. So if anyone can help please

我只放了变量和类的构造函数但它也有getter和setter。所以如果有人能帮忙请

6 个解决方案

#1


47  

Easy way to do it without annotations is to use Gson library

没有注释的简单方法是使用Gson库

Simple as that:

简单:

Gson gson = new Gson();
String json = gson.toJson(listaDePontos);

#2


6  

The quickest and easiest way I've found to Json-ify POJOs is to use the Gson library. This blog post gives a quick overview of using the library.

我找到的最快、最简单的方法是使用Gson库。这篇博文简要概述了如何使用这个库。

#3


3  

You make the http request

您发出http请求

HttpResponse response = httpclient.execute(httpget);           
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

You read the Buffer

你读到缓冲区

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
Log.d("Result", sb.toString());
result = sb.toString();

Create a JSONObject and pass the result string to the constructor:

创建一个JSONObject并将结果字符串传递给构造函数:

JSONObject json = new JSONObject(result);

Parse the json results to your desired variables:

将json结果解析为所需的变量:

String usuario= json.getString("usuario");
int idperon = json.getInt("idperson");
String nombre = json.getString("nombre");

Do not forget to import:

不要忘记输入:

import org.json.JSONObject;

#4


3  

GSON is easy to use and has relatively small memory footprint. If you loke to have even smaller footprint, you can grab:

GSON易于使用,内存占用也相对较小。如果你有更小的足迹,你可以抓住:

https://github.com/ko5tik/jsonserializer

https://github.com/ko5tik/jsonserializer

Which is tiny wrapper around stripped down GSON libraries for just POJOs

哪一个只是为了pojo而剥离GSON库的小包装

#5


2  

The "reference" Java implementation by Sean Leary is here on github. Make sure to have the latest version - different libraries pull in versions buggy old versions from 2009.

Sean Leary的“引用”Java实现在github上。确保有最新的版本——不同的库从2009年开始引入有bug的旧版本。

Java EE 7 has a JSON API in javax.json, see the Javadoc. From what I can tell, it doesn't have a simple method to marshall any object to JSON, you need to construct a JsonObject or a JsonArray.

Java EE 7在javax中有一个JSON API。json,看到Javadoc。从我所知道的情况来看,它没有一个简单的方法将任何对象转换为JSON,您需要构造一个JsonObject或JsonArray。

import javax.json.*;

JsonObject value = Json.createObjectBuilder()
 .add("firstName", "John")
 .add("lastName", "Smith")
 .add("age", 25)
 .add("address", Json.createObjectBuilder()
     .add("streetAddress", "21 2nd Street")
     .add("city", "New York")
     .add("state", "NY")
     .add("postalCode", "10021"))
 .add("phoneNumber", Json.createArrayBuilder()
     .add(Json.createObjectBuilder()
         .add("type", "home")
         .add("number", "212 555-1234"))
     .add(Json.createObjectBuilder()
         .add("type", "fax")
         .add("number", "646 555-4567")))
 .build();

JsonWriter jsonWriter = Json.createWriter(...);
jsonWriter.writeObject(value);
jsonWriter.close();

But I assume the other libraries like GSON will have adapters to create objects implementing those interfaces.

但是我假设像GSON这样的其他库会有适配器来创建实现这些接口的对象。

#6


0  

After JAVAEE8 published , now you can use the new JAVAEE API JSON-B (JSR367)

在JAVAEE8发布之后,现在您可以使用新的JAVAEE API JSON-B (JSR367)

Maven dependency :

Maven的依赖:

<dependency>
    <groupId>javax.json.bind</groupId>
    <artifactId>javax.json.bind-api</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>

Here is some code snapshot :

下面是一些代码快照:

Jsonb jsonb = JsonbBuilder.create();
// Two important API : toJson fromJson
String result = jsonb.toJson(listaDePontos);

JSON-P is also updated to 1.1 and more easy to use. JSON-P 1.1 (JSR374)

JSON-P也被更新为1.1并且更容易使用。JSON-P 1.1(JSR374)

Maven dependency :

Maven的依赖:

<dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.1</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>

Here is the runnable code snapshot :

下面是可运行代码快照:

String data = "{\"name\":\"Json\","
                + "\"age\": 29,"
                + " \"phoneNumber\": [10000,12000],"
                + "\"address\": \"test\"}";
        JsonObject original = Json.createReader(new StringReader(data)).readObject();
        /**getValue*/
        JsonPointer pAge = Json.createPointer("/age");
        JsonValue v = pAge.getValue(original);
        System.out.println("age is " + v.toString());
        JsonPointer pPhone = Json.createPointer("/phoneNumber/1");
        System.out.println("phoneNumber 2 is " + pPhone.getValue(original).toString());

#1


47  

Easy way to do it without annotations is to use Gson library

没有注释的简单方法是使用Gson库

Simple as that:

简单:

Gson gson = new Gson();
String json = gson.toJson(listaDePontos);

#2


6  

The quickest and easiest way I've found to Json-ify POJOs is to use the Gson library. This blog post gives a quick overview of using the library.

我找到的最快、最简单的方法是使用Gson库。这篇博文简要概述了如何使用这个库。

#3


3  

You make the http request

您发出http请求

HttpResponse response = httpclient.execute(httpget);           
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

You read the Buffer

你读到缓冲区

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
Log.d("Result", sb.toString());
result = sb.toString();

Create a JSONObject and pass the result string to the constructor:

创建一个JSONObject并将结果字符串传递给构造函数:

JSONObject json = new JSONObject(result);

Parse the json results to your desired variables:

将json结果解析为所需的变量:

String usuario= json.getString("usuario");
int idperon = json.getInt("idperson");
String nombre = json.getString("nombre");

Do not forget to import:

不要忘记输入:

import org.json.JSONObject;

#4


3  

GSON is easy to use and has relatively small memory footprint. If you loke to have even smaller footprint, you can grab:

GSON易于使用,内存占用也相对较小。如果你有更小的足迹,你可以抓住:

https://github.com/ko5tik/jsonserializer

https://github.com/ko5tik/jsonserializer

Which is tiny wrapper around stripped down GSON libraries for just POJOs

哪一个只是为了pojo而剥离GSON库的小包装

#5


2  

The "reference" Java implementation by Sean Leary is here on github. Make sure to have the latest version - different libraries pull in versions buggy old versions from 2009.

Sean Leary的“引用”Java实现在github上。确保有最新的版本——不同的库从2009年开始引入有bug的旧版本。

Java EE 7 has a JSON API in javax.json, see the Javadoc. From what I can tell, it doesn't have a simple method to marshall any object to JSON, you need to construct a JsonObject or a JsonArray.

Java EE 7在javax中有一个JSON API。json,看到Javadoc。从我所知道的情况来看,它没有一个简单的方法将任何对象转换为JSON,您需要构造一个JsonObject或JsonArray。

import javax.json.*;

JsonObject value = Json.createObjectBuilder()
 .add("firstName", "John")
 .add("lastName", "Smith")
 .add("age", 25)
 .add("address", Json.createObjectBuilder()
     .add("streetAddress", "21 2nd Street")
     .add("city", "New York")
     .add("state", "NY")
     .add("postalCode", "10021"))
 .add("phoneNumber", Json.createArrayBuilder()
     .add(Json.createObjectBuilder()
         .add("type", "home")
         .add("number", "212 555-1234"))
     .add(Json.createObjectBuilder()
         .add("type", "fax")
         .add("number", "646 555-4567")))
 .build();

JsonWriter jsonWriter = Json.createWriter(...);
jsonWriter.writeObject(value);
jsonWriter.close();

But I assume the other libraries like GSON will have adapters to create objects implementing those interfaces.

但是我假设像GSON这样的其他库会有适配器来创建实现这些接口的对象。

#6


0  

After JAVAEE8 published , now you can use the new JAVAEE API JSON-B (JSR367)

在JAVAEE8发布之后,现在您可以使用新的JAVAEE API JSON-B (JSR367)

Maven dependency :

Maven的依赖:

<dependency>
    <groupId>javax.json.bind</groupId>
    <artifactId>javax.json.bind-api</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>

Here is some code snapshot :

下面是一些代码快照:

Jsonb jsonb = JsonbBuilder.create();
// Two important API : toJson fromJson
String result = jsonb.toJson(listaDePontos);

JSON-P is also updated to 1.1 and more easy to use. JSON-P 1.1 (JSR374)

JSON-P也被更新为1.1并且更容易使用。JSON-P 1.1(JSR374)

Maven dependency :

Maven的依赖:

<dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.1</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>

Here is the runnable code snapshot :

下面是可运行代码快照:

String data = "{\"name\":\"Json\","
                + "\"age\": 29,"
                + " \"phoneNumber\": [10000,12000],"
                + "\"address\": \"test\"}";
        JsonObject original = Json.createReader(new StringReader(data)).readObject();
        /**getValue*/
        JsonPointer pAge = Json.createPointer("/age");
        JsonValue v = pAge.getValue(original);
        System.out.println("age is " + v.toString());
        JsonPointer pPhone = Json.createPointer("/phoneNumber/1");
        System.out.println("phoneNumber 2 is " + pPhone.getValue(original).toString());