Java 发送复杂的JSON对象
我想与web服务器通信并交换JSON信息 我的Web服务URL的格式如下所示:http://46.157.263.140/EngineTestingWCF/DPMobileBookingService.svc/SearchOnlyCus 这是我的JSON请求格式Java 发送复杂的JSON对象,java,android,json,web-services,gson,Java,Android,Json,Web Services,Gson,我想与web服务器通信并交换JSON信息 我的Web服务URL的格式如下所示:http://46.157.263.140/EngineTestingWCF/DPMobileBookingService.svc/SearchOnlyCus 这是我的JSON请求格式 { "f": { "Adults": 1, "CabinClass": 0, "ChildAge": [ 7 ], "Chi
{
"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"
}
我尝试使用以下代码发送请求:
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";
}
然后使用Gson创建JSON对象,如下所示:
我的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;
}
现在我得到了以下异常:
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)
如何解决此异常?提前谢谢 我对Json不太熟悉,但我知道它现在非常常用,而且您的代码似乎没有问题 如何将此JSON字符串转换为JSON对象 好了,您就快到了,只需将JSON字符串发送到您的服务器,然后在服务器中再次使用Gson:
Gson gson = new Gson();
Fpack f = gson.fromJSON(json, Fpack.class);
关于例外情况:
您应该删除此行,因为您正在发送请求,而不是响应请求:
httpPostRequest.setHeader("Accept", "application/json");
我会改变这句话:
httpPostRequest.setHeader("Content-type", "application/json");
到
如果这没有任何区别,请在发送请求之前打印出JSON字符串,让我们看看里面有什么。我对JSON不太熟悉,但我知道它现在非常常用,而且您的代码似乎没有问题 如何将此JSON字符串转换为JSON对象 好了,您就快到了,只需将JSON字符串发送到您的服务器,然后在服务器中再次使用Gson:
Gson gson = new Gson();
Fpack f = gson.fromJSON(json, Fpack.class);
关于例外情况:
您应该删除此行,因为您正在发送请求,而不是响应请求:
httpPostRequest.setHeader("Accept", "application/json");
我会改变这句话:
httpPostRequest.setHeader("Content-type", "application/json");
到
如果这没有任何区别,请在发送请求之前打印出JSON字符串,让我们看看里面有什么。要创建附加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);
}
要创建附加有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);
}
据我所知,您希望使用您创建的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();
}
}
}
据我所知,您希望使用您创建的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();
}
}
}
事实上,这是一个错误的要求。这就是服务器以XML格式返回响应的原因。 问题是将非原语dataDATE转换为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));
}
};
事实上,这是一个错误的要求。这就是服务器以XML格式返回响应的原因。 问题是将非原语dataDATE转换为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));
}
};
谢谢你的回答。但是当我将json字符串发送到服务器时,我得到了警告org.json.JSONException:Value@bala如何发送此字符串?您在服务器端还是客户端收到异常?//您在服务器端还是客户端收到异常?//我在客户端收到异常//如何发送此字符串?//我更新了关于此的问题。。请看..帮我..就像你说的我做了改变,但现在我得到了这个例外。。org.json.JSONException:Value!java.lang.String类型的DOCTYPE无法转换为org.json.json.typemistmatchjson.java:111在org.json.JSONObject.JSONObject.java:158在org.json.JSONObject.JSONObject.java:171我在发送请求之前更新json字符串的打印输出,请参阅..@bala-从您发布的两个异常堆栈跟踪中,JSON字符串中可能有一些隐藏的XML内容。您是否使用JSON对象在服务器端转换传入的JSON字符串?请将服务器端的完整资源方法发布到您的问题中。谢谢您的回答。但是当我将json字符串发送到服务器时,我得到了警告org.json.JSONException:Value@bala如何发送此字符串?您在服务器端还是客户端收到异常?//您在服务器端还是客户端收到异常?//我在客户端收到异常//如何发送此字符串?//我更新了关于此的问题。。请看..帮我..就像你说的我做了改变,但现在我得到了这个例外。。org.json.JSONException:Value!java.lang.String类型的DOCTYPE无法转换为org.json.json.typemistmatchjson.java:111在org.json.JSONObject.JSONObject.java:158在org.json.JSONObject.JSONObject.java:171我在发送请求之前更新json字符串的打印输出,请参阅..@bala-从您发布的两个异常堆栈跟踪中,JSON字符串中可能有一些隐藏的XML内容。您是否使用JSON对象在服务器端转换传入的JSON字符串?请将服务器端的完整资源方法发布到您的问题中。这对我来说很有效,而不是使用StringEntity+1.这对我有效,而不是使用StringEntity+1.