Json对象数组映射

时间:2017-05-18 21:54:34

标签: java json gson resttemplate

我有一个POJO用于​​映射json到GSON,如下所示:

public class Email {
    private String emailFrom;
    private String[] emailTo;
    private String subject;

    //getters and setters 
}

接下来我在我的客户端应用程序中创建这样的JSON对象:

JSONObject basicParams = new JSONObject();
basicParams.put("emailFrom", "abc@gmail.com ");

String[] emailnew= {"cde@gmail.com ","fgh@gmail.com"};
basicParams.put("emailTo", emailnew);
basicParams.put("subject", "Test GSON");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers);// converting the json object toString here seems to be the issue
ResponseEntity<String> response = restTemplate.exchange(testUrl, HttpMethod.POST, entity, String.class);

在我的控制器中,我这样做:

Gson gson = new GsonBuilder().create();
Email email = gson.fromJson(json, Email.class);

它投掷错误。 我调试时,我的JSON看起来像这样:

"basic" -> " {"templateName":"masterTemplate","subject":"Test GSON","emailFrom":"abc@gmail.com","emailTo":"[Ljava.lang.String;@1dc2c13c"}"

为什么它有对象引用?我怎样才能保持实际值?

3 个答案:

答案 0 :(得分:0)

这取决于您使用的库。您似乎在键值对的值中输入数组:

basicParams.put("emailTo", emailnew);

但是你在其他条目中输入了Strings。你能提供图书馆的链接吗?

答案 1 :(得分:0)

您的第一个JSON库不知道如何处理数组。它只是在上面调用toString()。您需要将数组包装到List对象中:

basicParams.put("emailTo", Arrays.asList(emailnew));

答案 2 :(得分:0)

我认为您的JSONObject来自JSON in Java。我的试验似乎没有任何问题。这是我的代码:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import org.json.JSONObject;

class Email {
    private String emailFrom;
    private String[] emailTo;
    private String subject;

    public String getEmailFrom() {
        return emailFrom;
    }

    public String[] getEmailTo() {
        return emailTo;
    }

    public String getSubject() {
        return subject;
    }
}

public class Main {

    public static void main(String[] args) {
        JSONObject basicParams = new JSONObject();
        basicParams.put("emailFrom", "abc@gmail.com ");
        String[] emailnew= {"cde@gmail.com ","fgh@gmail.com"};
        basicParams.put("emailTo", emailnew);
        basicParams.put("subject", "Test GSON");

        String json = basicParams.toString();
        System.out.println(json);

        Gson gson = new GsonBuilder().create();
        Email email = gson.fromJson(json, Email.class);
        System.out.println(email.getEmailFrom());
        for (String emailTo : email.getEmailTo()) {
            System.out.println(emailTo);
        }
        System.out.println(email.getSubject());
    }
}

输出是:

{"subject":"Test GSON","emailFrom":"abc@gmail.com ","emailTo":["cde@gmail.com ","fgh@gmail.com"]}
abc@gmail.com 
cde@gmail.com 
fgh@gmail.com
Test GSON

这看起来很正常。我正在使用最新版本的库(JSON in Java和Gson)直接从maven central herehere下载。

关键是你如何在客户端和服务器之间进行通信?在你的情况下,沟通可能很复杂,与我的简单String json = basicParams.toString();相反。我认为这里出了点问题,使解析报告错误。