【问题标题】:What will be the structure of JSON string inside POST arrayPOST数组中JSON字符串的结构是什么
【发布时间】:2014-03-06 10:02:17
【问题描述】:

这是我的 Java 程序,它试图将 JSON 对象发送到服务器。我使用 Apache HTTPClient 处理 HTTP 请求,使用 Jettison 作为 JSON 库。

我对此没有什么疑问。

  1. POST 数组中 JSON 字符串的结构是什么。类似{xxxxx:{userId:userId, blha, blha, blha.........}}

  2. 如果我只需要从服务器端的 POST 数组中获取 JSON 字符串(无需转换为对象)。怎么做?在php中我们这样做echo $_POST["xxxxxxx"];

  3. 通常 POST 数组中的每个数据都有一个名称。但下面的程序没有为 JSON 对象指定任何名称。 POST 数组中以下 JSON 字符串的名称(xxxxxxx)是什么。


string base_url = "https://abc.com/";
string username = "test_user";
string password = "test_user_pw";
string client_id = "test_user123";
string client_secret = "test_user1234567";
string login_url = base_url + "session/login";

CloseableHttpClient wf_client = HttpClients.custom().setUserAgent(client_id + "/1.0").build();
HttpPost login_post = new HttpPost(loginUrl);
JSONObject login_object = new JSONObject();
try {
    login_object.put("userId", username);
    login_object.put("password", password);
    login_object.put("clientId", client_id);
    login_object.put("clientSecret", client_secret);
} catch (JSONException ex) {
    System.out.println(ex.toString());
}

StringEntity post_entity = new StringEntity(login_object.toString(), jason_content_type);
login_post.setEntity(post_entity);
CloseableHttpResponse responce = wf_client.execute(login_post);

【问题讨论】:

    标签: java json apache-httpclient-4.x jettison


    【解决方案1】:

    按照相同的结构回答您的问题

    • 你是对的,这就是JSON字符串的结构。确切的语法可以在JSON.org website 中找到。

    例子:

    { 
       "userId" : "Username",
       "array"  : [ "1", "2", "3" ],
       "object" : {
          "objectId" : "bkadakdbk",
          ...
       }
    }
    
    • 在 Java 中,您必须读取来自服务器端(通常是 servlet)的 HTTP 请求中的数据:

    例子:

    BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    
    • 在 Java 中,当您发出这样的 POST 请求时,通常会将 JSON 对象作为请求的内容发送,因此服务器端没有参数数组,这就是您必须读取请求本身的内容的原因和我之前的例子一样。

    【讨论】:

    • 感谢您的回答。但是You are right, that's the structure of JSON string 是什么意思?我正在寻找字符串的确切结构。如果我需要通过连接字符串来生成相同的 JSON 字符串。格式是什么?
    • @NayanaAdassuriya 啊,好的。然后查看我更新的答案,我添加了一个指向确切 JSON 语法的链接和一个示例。希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    相关资源
    最近更新 更多