Java 如何在 URL 中将 JSON 数组作为参数传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27577922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:37:58  来源:igfitidea点击:

How to pass a JSON array as a parameter in URL

javajsonspringweb-services

提问by rocking

I have an requirement to pass a some values from mobile to server in a web service call and so I am planning to pass all the values in JSON format like the below

我需要在 Web 服务调用中将一些值从移动设备传递到服务器,因此我计划以 JSON 格式传递所有值,如下所示

{
    "nameservice": [
        {
            "id": 7413,
            "name": "ask"
        },
        {
            "id": 7414,
            "name": "josn"
        },
        {
            "id": 7415,
            "name": "john"
        },
        {
            "id": 7418,
            "name": "R&R"
        }
    ]
}

The following is my service call

以下是我的服务电话

@RequestMapping("/saveName")
@ResponseBody
public String saveName(String acc)
{jsonObject = new JSONObject();
    try
    {
    );
    System.out.println(acc);
    jsonObject.accumulate("result", "saved ");
    }
    catch(Exception e)
    {
        e.printStackTrace();jsonObject.accumulate("result", "Error Occured ");
    }
    return jsonObject.toString();
}

I am trying to call the above service by this way

我正在尝试通过这种方式调用上述服务

localhost:8080/service/saveName?acc={ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "R&R" } ] }

But the output is like this

但是输出是这样的

{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "R

Can any body please tell me why I am not getting all the values please?

任何机构都可以告诉我为什么我没有得到所有的价值吗?

采纳答案by RE350

I would suggest to pass the JSON data in the body as a POSTrequest.But if you still want to pass this as a parameter in URL,you will have to encode your URL like below just for example:-

我建议将主体中的 JSON 数据作为POST请求传递。但是如果您仍然想将其作为 URL 中的参数传递,则必须像下面这样对您的 URL 进行编码,例如:-

for ex json is :->{"name":"ABC","id":"1"}

对于前 json 是:->{"name":"ABC","id":"1"}

testurl:80/service?data=%7B%22name%22%3A%22ABC%22%2C%22id%22%3A%221%22%7D

testurl:80/service?data=%7B%22name%22%3A%22ABC%22%2C%22id%22%3A%221%22%7D

for more information on URL encoding refer below

有关 URL 编码的更多信息,请参阅下文

https://en.wikipedia.org/wiki/Percent-encoding

https://en.wikipedia.org/wiki/Percent-encoding

回答by wgitscht

& is a keyword for the next parameter like this ur?param1=1&param2=2

& 是下一个参数的关键字,例如 ur?param1=1¶m2=2

so effectively you send a second param named R". You should urlencodeyour string. Isn't POST an option?

如此有效地您发送了第二个名为 R" 的参数。您应该使用urlencode您的字符串。POST 不是一个选项吗?

回答by pintu

You can pass your json Input as a POST request along with authorization header in this way

您可以通过这种方式将您的 json 输入作为 POST 请求与授权标头一起传递

public static JSONObject getHttpConn(String json){
        JSONObject jsonObject=null;
        try {
            HttpPost httpPost=new HttpPost("http://google.com/");
            org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
            StringEntity stringEntity=new StringEntity("d="+json);

            httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
            String authorization="test:test@123";
            String encodedAuth = "Basic " + Base64.encode(authorization.getBytes());        
            httpPost.addHeader("Authorization", security.get("Authorization"));
            httpPost.setEntity(stringEntity);
            HttpResponse reponse=client.execute(httpPost);
            InputStream inputStream=reponse.getEntity().getContent();
            String jsonResponse=IOUtils.toString(inputStream);
            jsonObject=JSONObject.fromObject(jsonResponse);
            } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        } catch (ClientProtocolException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
        return jsonObject;


    }

This Method will return a json response.In same way you can use GET method

此方法将返回一个 json 响应。以同样的方式您可以使用 GET 方法

回答by u557022

As @RE350 suggested passing the JSON data in the body in the post would be ideal. However, you could still send the json object as a parameter in a GET request, decode the json string in the server-side logic and use it as an object.

由于@RE350 建议在帖子的正文中传递 JSON 数据将是理想的。但是,您仍然可以将 json 对象作为 GET 请求中的参数发送,在服务器端逻辑中解码 json 字符串并将其用作对象。

For example, if you are on php you could do this (use the appropriate json decode in other languages):

例如,如果您使用的是 php,则可以执行此操作(使用其他语言中的相应 json 解码):

Server request:

服务器请求:

http://<php script>?param1={"nameservice":[{"id":89},{"id":3}]}

In the server:

在服务器中:

$obj = json_decode($_GET['param1'], true);
$obj["nameservice"][0]["id"]

out put:

输出:

89

回答by Ali Eshghi

Send Json data string to a web address and get a result with method post

将 Json 数据字符串发送到网址并使用方法 post 获取结果

in C#

在 C# 中

public string SendJsonToUrl(string Url, string StrJsonData)
{
    if (Url == "" || StrJsonData == "") return "";
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.ContentLength = StrJsonData.Length;
        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            streamWriter.Write(StrJsonData);
            streamWriter.Close();
            var httpResponse = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                return result;
            }
        }
    }
    catch (Exception exp)
    {
        throw new Exception("SendJsonToUrl", exp);
    }
}

in PHP

在 PHP 中

<?php

$input = file_get_contents('php://input');
$json = json_decode($input ,true);

?>

回答by gvelasquez85

I know this could be a later post, but, for new visitors I will share my solution, as the OP was asking for a way to pass a JSON object via GET (not POST as suggested in other answers).

我知道这可能是稍后的帖子,但是,对于新访问者,我将分享我的解决方案,因为 OP 要求一种通过 GET 传递 JSON 对象的方法(而不是其他答案中建议的 POST)。

  1. Take the JSON object and convert it to string (JSON.stringify)
  2. Take the string and encode it in Base64 (you can find some useful info on this here
  3. Append it to the URL and make the GET call
  4. Reverse the process. decode and parse it into an object
  1. 获取 JSON 对象并将其转换为字符串 (JSON.stringify)
  2. 获取字符串并将其编码为 Base64(您可以在此处找到一些有用的信息)
  3. 将其附加到 URL 并进行 GET 调用
  4. 颠倒这个过程。解码并将其解析为一个对象

I have used this in some cases where I only can do GET calls and it works. Also, this solution is practically cross language.

我在某些情况下使用过它,在这种情况下我只能进行 GET 调用并且它可以工作。此外,该解决方案实际上是跨语言的。

回答by him khy

I know this could be a later post, but, for new visitors I will share my solution, as the OP was asking for a way to pass a JSON object via GET (not POST as suggested in other answers)

我知道这可能是稍后的帖子,但是,对于新访问者,我将分享我的解决方案,因为 OP 要求一种通过 GET 传递 JSON 对象的方法(而不是其他答案中建议的 POST)

1.the JSON object and convert it to string (JSON.stringify) 2.the string and encode it in Base64 (you can find some useful info on this here

1. JSON 对象并将其转换为字符串 (JSON.stringify) 2. 字符串并将其编码为 Base64(您可以在此处找到一些有用的信息)

  1. Append it to the URL and make the GET call Reverse the process. decode and parse it into an object
  1. 将其附加到 URL 并进行 GET 调用 反转该过程。解码并将其解析为一个对象

回答by Sundeep Dangol

I know this is old, but if anyone else wants to know why they get incomplete json like above is because the ampersand &is a special character in URLs used to separate parameters.
In your data there is an ampersand in R&R. So the acc parameter ends when it reaches the ampersand character.

我知道这是旧的,但是如果其他人想知道为什么他们得到像上面那样不完整的 json 是因为&符号&是用于分隔参数的 URL 中的特殊字符。
在您的数据中有一个&符号R&R。所以 acc 参数在到达 & 字符时结束。

That's why you are getting chopped data. The solution is either url encode the data or send as POST like the accepted solution suggests.

这就是为什么你会得到切碎的数据。解决方案是对数据进行 url 编码,或者像公认的解决方案建议的那样作为 POST 发送。

回答by plutomusang

let qs = event.queryStringParameters;
const query = Object.keys(qs).map(key => key + '=' + qs[key]).join('&');

回答by Vadorequest

I encountered the same need and make a universal solution (node+browser) that works with the Next.js framework, for instance.

例如,我遇到了同样的需求并制定了一个适用于 Next.js 框架的通用解决方案(节点 + 浏览器)。

It even works with circular dependencies (thanks to json-stringify-safe).

它甚至适用于循环依赖(感谢json-stringify-safe)。

Although, I also built a serializer on top of it to remove unnecessary data (because it's not recommended to use a url longer than 2k chars, see What is the maximum length of a URL in different browsers?)

虽然,我还在它上面构建了一个序列化程序来删除不必要的数据(因为不建议使用超过 2k 个字符的 url,请参阅不同浏览器中 URL 的最大长度是多少?

import StringifySafe from 'json-stringify-safe';

export const encodeQueryParameter = (data: object): string => {
  return encodeURIComponent(StringifySafe(data)); // Use StringifySafe to avoid crash on circular dependencies
};

export const decodeQueryParameter = (query: string): object => {
  return JSON.parse(decodeURIComponent(query));
};


And the unit tests (jest):

和单元测试(开玩笑):

import { decodeQueryParameter, encodeQueryParameter } from './url';

export const data = {
  'organisation': {
    'logo': {
      'id': 'ck2xjm2oj9lr60b32c6l465vx',
      'linkUrl': null,
      'linkTarget': '_blank',
      'classes': null,
      'style': null,
      'defaultTransformations': { 'width': 200, 'height': 200, '__typename': 'AssetTransformations' },
      'mimeType': 'image/png',
      '__typename': 'Asset',
    },
    'theme': {
      'primaryColor': '#1134e6',
      'primaryAltColor': '#203a51',
      'secondaryColor': 'white',
      'font': 'neuzeit-grotesk',
      '__typename': 'Theme',
      'primaryColorG1': '#ffffff',
    },
  },
};
export const encodedData = '%7B%22organisation%22%3A%7B%22logo%22%3A%7B%22id%22%3A%22ck2xjm2oj9lr60b32c6l465vx%22%2C%22linkUrl%22%3Anull%2C%22linkTarget%22%3A%22_blank%22%2C%22classes%22%3Anull%2C%22style%22%3Anull%2C%22defaultTransformations%22%3A%7B%22width%22%3A200%2C%22height%22%3A200%2C%22__typename%22%3A%22AssetTransformations%22%7D%2C%22mimeType%22%3A%22image%2Fpng%22%2C%22__typename%22%3A%22Asset%22%7D%2C%22theme%22%3A%7B%22primaryColor%22%3A%22%231134e6%22%2C%22primaryAltColor%22%3A%22%23203a51%22%2C%22secondaryColor%22%3A%22white%22%2C%22font%22%3A%22neuzeit-grotesk%22%2C%22__typename%22%3A%22Theme%22%2C%22primaryColorG1%22%3A%22%23ffffff%22%7D%7D%7D';

describe(`utils/url.ts`, () => {
  describe(`encodeQueryParameter`, () => {
    test(`should encode a JS object into a url-compatible string`, async () => {
      expect(encodeQueryParameter(data)).toEqual(encodedData);
    });
  });

  describe(`decodeQueryParameter`, () => {
    test(`should decode a url-compatible string into a JS object`, async () => {
      expect(decodeQueryParameter(encodedData)).toEqual(data);
    });
  });

  describe(`encodeQueryParameter <> decodeQueryParameter <> encodeQueryParameter`, () => {
    test(`should encode and decode multiple times without altering data`, async () => {
      const _decodedData: object = decodeQueryParameter(encodedData);
      expect(_decodedData).toEqual(data);

      const _encodedData: string = encodeQueryParameter(_decodedData);
      expect(_encodedData).toEqual(encodedData);

      const _decodedDataAgain: object = decodeQueryParameter(_encodedData);
      expect(_decodedDataAgain).toEqual(data);
    });
  });
});