gpt4 book ai didi

java - 将 JSON 发送到 Rails

转载 作者:行者123 更新时间:2023-12-01 14:47:59 26 4
gpt4 key购买 nike

我的问题是转义字符使我的 JSON 无效。我正在将 JSON 发送到 Rails 服务器,但当它到达时,它会获得一些转义字符。

我可以做些什么来解决我的restfull类上的这个问题,还是需要在服务器端进行纠正?

这是我发送的 JSON,

[session={"password":"********","email":"********@omobile.com.br"}]

这是出现在服务器日志上的 JSON:

{"session"=>"{\"password\":\"********\",\"email\":\"********@omobile.com.br\"}"}

我尝试了这些不同的方式来发送 JSON,结果是相同的:

JSONObject object = new JSONObject();
object.accumulate("email", username);
object.accumulate("password", password);
String jsonString = object.toString();

Session session = new Session();
session.setEmail(username);
session.setPassword(password);
Gson gson = new Gson();
String jsonString = gson.toJson(session, Session.class);

最佳答案

发生的事情很困惑,因为您发布的字符串实际上都不是 JSON。第一个实际上我不知道它是什么,而第二个可能意味着在 Ruby 端你有这个 Ruby 哈希,其中键“session”指的是 JSON 编码的哈希。

我们无法判断线路上发生了什么,因为您没有发布代码,因此我们无法判断您的服务器是否需要表单编码的请求正文、多部分请求正文,或者直接是 JSON 编码的对象.

我希望您考虑到我看到的唯一 JSON 是以下部分:

{"password": "********","email":"********@omobile.com.br"}

正如我所说,这可以按原样传递,也可以作为多部分信封的一部分传递,甚至可以进行 url 编码。该格式实际上是在服务器上建立的。例如,我使用 Apache HttpClient 进行了快速测试:

public class GsonSendToSinatra {

private static class Session {
@SuppressWarnings("unused")
String username, password;
}

public static void main(String[] args) throws Exception {
Session session = new Session();
session.username = "foo@example.com";
session.password = "qwerty1234";

Gson gson = new Gson();

String responseText = Request.Post("http://localhost:4567/echo")
.bodyString(gson.toJson(session), ContentType.APPLICATION_JSON)
.execute()
.returnContent()
.asString();

System.out.println(responseText);
}
}

服务器上的 Sinatra:

require 'sinatra'
require 'json'

post '/echo' do
content_type "text/plain"
layout false

session = JSON.parse request.body.read

session.map {|k,v| "#{k}: #{v}\n"}
end

我希望这个示例可以帮助您了解 HTTP 对话中的 Activity 部分以及如何组合它们。

关于java - 将 JSON 发送到 Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15212988/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com