我需要將以下Json代碼轉換爲Java。在Java中格式化Json代碼
{
"service": {
"type": "nyd",
"discount": 0.20,
"items": [
{
"asin": "....",
"link": "http://amazon.com/.....",
"quantity": 2
},
// ...
],
// See /addresses
"shipping_address": {
"full_name": "Mr Smith",
"street1": "Some Mission St",
"street2": "", // Optional
"city": "San Francisco",
"state": "CA",
"zip": "94000",
"country": "US",
"phone": "1234567890"
}
}
}
我目前使用下面的代碼實現這一點:
String postUrl = "https://API.example.com";
Gson gson = new Gson();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPostRequest = new HttpPost(postUrl);
StringEntity postingString = new StringEntity("{\"service\" : {\"type\":\"nnn\", \"discount\":" + 0.2 + ",\"items\" : [ { \"asin\":\"B018Y1XXT6\", \"link\":\"http://rads.stackoverflow.com/amzn/click/B018Y1XXT6", \"quantity\":" + 1 + " } ], \"shipping_address\" : {\"full_name\":\"Steven Smith\", \"street1\":\"11 Man Rd\", \"street2\":\"\", \"city\":\"Woonsocket\", \"state\":\"RI\", \"zip\":\"02844\", \"country\":\"US\", \"phone\":\"7746536483\" } } } ");
Mote: the values are different but I'm trying to achieve the same syntax.
System.out.println("Post String value: " + IOUtils.toString(postingString.getContent()));
httpPostRequest.addHeader("Authorization", "Token " + apiKey);
httpPostRequest.setEntity(postingString);
httpPostRequest.setHeader("Content-type", "application/json");
//httpPostRequest.addHeader("content-type", "application/x-www-form-urlencoded");
HttpResponse response = httpClient.execute(httpPostRequest);
System.out.println(response.toString());
的 「postString」 值是:
{"service" : {"type":"nnn", "discount":0.2,"items" : [ { "asin":"B018Y1XXT6", "link":"http://rads.stackoverflow.com/amzn/click/B018Y1XXT6", "quantity":1 } ], "shipping_address" : {"full_name":"Steven Smith", "street1":"11 Man Rd", "street2":"", "city":"Woonsocket", "state":"RI", "zip":"02844", "country":"US", "phone":"17746536483" } } }
然而,當我試圖提交請求我得到一個錯誤的請求錯誤。
如何正確格式化字符串?
感謝
'服務='看起來對我來說很可疑。服務是json對象的一部分,所以我認爲你的StringEntity應該以'{\「service \」開始:'並且在末尾有相應的終止大括號。好像postString的值應該是'{「service」:{「type」:「nyd」,「....' – DaveH