java 发送复杂的 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15171454/
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-10-31 18:42:58  来源:igfitidea点击:

Sending Complex JSON Object

javaandroidjsonweb-servicesgson

提问by bCliks

I want to communicate with a web server and exchange JSON information.

我想与 Web 服务器通信并交换 JSON 信息。

my webservice URL looking like following format: http://46.157.263.140/EngineTestingWCF/DPMobileBookingService.svc/SearchOnlyCus

我的网络服务 URL 看起来像以下格式: http://46.157.263.140/EngineTestingWCF/DPMobileBookingService.svc/SearchOnlyCus

Here is my JSON Request format.

这是我的 JSON 请求格式。

{
    "f": {
        "Adults": 1,
        "CabinClass": 0,
        "ChildAge": [
            7
        ],
        "Children": 1,
        "CustomerId": 0,
        "CustomerType": 0,
        "CustomerUserId": 81,
        "DepartureDate": "/Date(1358965800000+0530)/",
        "DepartureDateGap": 0,
        "Infants": 1,
        "IsPackageUpsell": false,
        "JourneyType": 2,
        "PreferredCurrency": "INR",
        "ReturnDate": "/Date(1359138600000+0530)/",
        "ReturnDateGap": 0,
        "SearchOption": 1
    },
    "fsc": "0"
}

I tried with the following code to send a request:

我尝试使用以下代码发送请求:

public class Fdetails {
    private String Adults = "1";
    private String CabinClass = "0";
    private String[] ChildAge = { "7" };
    private String Children = "1";
    private String CustomerId = "0";
    private String CustomerType = "0";
    private String CustomerUserId = "0";
    private Date DepartureDate = new Date();
    private String DepartureDateGap = "0";
    private String Infants = "1";
    private String IsPackageUpsell = "false";
    private String JourneyType = "1";
    private String PreferredCurrency = "MYR";
    private String ReturnDate = "";
    private String ReturnDateGap = "0";
    private String SearchOption = "1";
}

public class Fpack {
    private Fdetails f = new Fdetails();
    private String fsc = "0";
}

Then using Gson I create the JSON objectlike:

然后使用 Gson 我创建JSON 对象,如:

public static String getJSONString(String url) {
String jsonResponse = null;
String jsonReq = null;
Fpack fReq = new Fpack();

try {                                                
    Gson gson = new Gson();
    jsonReq = gson.toJson(fReq);                        
    JSONObject json = new JSONObject(jsonReq);
    JSONObject jsonObjRecv = HttpClient.SendHttpPost(url, json);
    jsonResponse = jsonObjRecv.toString();
} 
catch (JSONException e) {
                           e.printStackTrace();
                }               
return jsonResponse;
    }

and my HttpClient.SendHttpPostmethod is

我的HttpClient.SendHttpPost方法是

public static JSONObject SendHttpPost(String URL, JSONObject json) {

        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPostRequest = new HttpPost(URL);

            StringEntity se;
            se = new StringEntity(json.toString());
            httpPostRequest.setEntity(se);
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));          
            HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // Read the content stream
                InputStream instream = entity.getContent();
                Header contentEncoding = response.getFirstHeader("Content-Encoding");
                if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                    instream = new GZIPInputStream(instream);
                }

                // convert content stream to a String
                String resultString= convertStreamToString(instream);
                instream.close();
                resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

                // Transform the String into a JSONObject
                JSONObject jsonObjRecv = new JSONObject(resultString);
            return jsonObjRecv;
            } 
    catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

Now I get the following exception:

现在我得到以下异常:

org.json.JSONException: Value !DOCTYPE of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:158)
at org.json.JSONObject.<init>(JSONObject.java:171)

and the printout of JSON string right before I make the request is as follows:

在我发出请求之前,JSON 字符串的打印输出如下:

{
    "f": {
        "PreferredCurrency": "MYR",
        "ReturnDate": "",            
        "ChildAge": [
            7
        ],
        "DepartureDate": "Mar 2, 2013 1:17:06 PM",
        "CustomerUserId": 0,
        "CustomerType": 0,
        "CustomerId": 0,
        "Children": 1,
        "DepartureDateGap": 0,
        "Infants": 1,
        "IsPackageUpsell": false,
        "JourneyType": 1,
        "CabinClass": 0,
        "Adults": 1,
        "ReturnDateGap": 0,
        "SearchOption": 1

    },
    "fsc": "0"
}

How do I solve this exception? Thanks in advance!

我该如何解决这个异常?提前致谢!

采纳答案by bCliks

Actually it was a BAD REQUEST. Thats why server returns response as XML format. The problem is to convert the non primitive data(DATE) to JSON object.. so it would be Bad Request.. I solved myself to understand the GSON adapters.. Here is the code I used:

实际上,这是一个错误的请求。这就是服务器以 XML 格式返回响应的原因。问题是将非原始数据(DATE)转换为 JSON 对象..所以这将是错误的请求..我解决了自己理解 GSON 适配器..这是我使用的代码:

try {                                                       
                        JsonSerializer<Date> ser = new JsonSerializer<Date>() {

                            @Override
                            public JsonElement serialize(Date src, Type typeOfSrc,
                                    JsonSerializationContext comtext) {

                                return src == null ? null : new JsonPrimitive("/Date("+src.getTime()+"+05300)/");
                            }
                        };
                        JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {                           
                            @Override
                            public Date deserialize(JsonElement json, Type typeOfT,
                                    JsonDeserializationContext jsonContext) throws JsonParseException {

                                String tmpDate = json.getAsString();

                                  Pattern pattern = Pattern.compile("\d+");
                                  Matcher matcher = pattern.matcher(tmpDate);
                                  boolean found = false;

                                  while (matcher.find() && !found) {
                                       found = true;
                                        tmpDate = matcher.group();
                                  }
                                return json == null ? null : new Date(Long.parseLong(tmpDate));                             
                            }
                        };

回答by WoooHaaaa

I'm not quite familiar with Json, but I know it's pretty commonly used today, and your code seems no problem.

我对 Json 不是很熟悉,但我知道它今天很常用,而且您的代码似乎没有问题。

How to convert this JSON string to JSON object?

如何将此 JSON 字符串转换为 JSON 对象?

Well, you almost get there, just send the JSON string to your server, and use Gson again in your server:

好吧,你快到了,只需将 JSON 字符串发送到您的服务器,然后在您的服务器中再次使用 Gson:

Gson gson = new Gson();
Fpack f = gson.fromJSON(json, Fpack.class);

http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html

http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html

About the Exception:

关于异常:

You should remove this line, because you are sending a request, not responsing to one:

您应该删除这一行,因为您正在发送一个请求,而不是响应一个:

httpPostRequest.setHeader("Accept", "application/json");

And I would change this line:

我会改变这一行:

httpPostRequest.setHeader("Content-type", "application/json"); 

to

se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

If this doesn't make any difference, please print out your JSON string before you send the request, let's see what's in there.

如果这没有任何区别,请在发送请求之前打印出您的 JSON 字符串,让我们看看里面有什么。

回答by Emil Adz

To create a request with JSON object attached to it what you should do is the following:

要创建附加了 JSON 对象的请求,您应该执行以下操作:

public static String sendComment (String commentString, int taskId, String    sessionId, int displayType, String url) throws Exception
{
    Map<String, Object> jsonValues = new HashMap<String, Object>();
    jsonValues.put("sessionID", sessionId);
    jsonValues.put("NewTaskComment", commentString);
    jsonValues.put("TaskID" , taskId);
    jsonValues.put("DisplayType" , displayType);
    JSONObject json = new JSONObject(jsonValues);

    DefaultHttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost(url + SEND_COMMENT_ACTION);

    AbstractHttpEntity entity = new ByteArrayEntity(json.toString().getBytes("UTF8"));
    entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    post.setEntity(entity);
    HttpResponse response = client.execute(post);

    return getContent(response);    
}

回答by vikasing

From what I have understood you want to make a request to the server using the JSON you have created, you can do something like this:

据我了解,您想使用您创建的 JSON 向服务器发出请求,您可以执行以下操作:

URL url;
    HttpURLConnection connection = null;
    String urlParameters ="json="+ jsonSend;  
    try {
      url = new URL(targetURL);
      connection = (HttpURLConnection)url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", 
           "application/x-www-form-urlencoded");
      connection.setRequestProperty("Content-Language", "en-US");  
      DataOutputStream wr = new DataOutputStream (
                  connection.getOutputStream ());
      wr.writeBytes (urlParameters);
      wr.flush ();
      wr.close ();

      InputStream is = connection.getInputStream();
      BufferedReader rd = new BufferedReader(new InputStreamReader(is));
      String line;
      StringBuffer response = new StringBuffer(); 
      while((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
      }
      rd.close();
      return response.toString();

    } catch (Exception e) {

      e.printStackTrace();
      return null;

    } finally {

      if(connection != null) {
        connection.disconnect(); 
      }
    }
  }