Я на вызов POST и ответ, который я получаю это:Extract значение конкретного ключа от Java HashMap
{"atoken":"32ab3a8738a4b57165b5fc863af4f4c95198c2c9","utoken":"9a3682e9eac186d56b230d075e7dc0d784992231"}
Код, который используется для осуществления вызова POST является:
try{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost3 = new HttpPost("http://www.mywebsite.com/adkh.json");
Log.i("Inside TokenPost", "Inside TokenPost");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("mobile", "989876556789"));
nameValuePair.add(new BasicNameValuePair("imei", "911239987651238"));
nameValuePair.add(new BasicNameValuePair("stoken", mtokenno));
//
try {
httpPost3.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
//
// Execute HTTP Post Request
try{
HttpResponse response = httpclient.execute(httpPost3);
Log.i("Response from Http Post Request", "Response from Http Post Request: "+ response);
System.out.println("Response: " +response.toString());
Log.i("Starting BufferedReader", "Starting BufferedReader");
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
System.out.println(line);
Я преобразование ответа от приведенной выше коды в Java хэш:
class NaturalDeserializer implements JsonDeserializer<Object> {
public Object deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) {
if(json.isJsonNull()) return null;
else if(json.isJsonPrimitive()) return handlePrimitive(json.getAsJsonPrimitive());
else if(json.isJsonArray()) return handleArray(json.getAsJsonArray(), context);
else return handleObject(json.getAsJsonObject(), context);
}
private Object handlePrimitive(JsonPrimitive json) {
if(json.isBoolean())
return json.getAsBoolean();
else if(json.isString())
return json.getAsString();
else {
BigDecimal bigDec = json.getAsBigDecimal();
// Find out if it is an int type
try {
bigDec.toBigIntegerExact();
try { return bigDec.intValueExact(); }
catch(ArithmeticException e) {}
return bigDec.longValue();
} catch(ArithmeticException e) {}
// Just return it as a double
return bigDec.doubleValue();
}
}
private Object handleArray(JsonArray json, JsonDeserializationContext context) {
Object[] array = new Object[json.size()];
for(int i = 0; i < array.length; i++)
array[i] = context.deserialize(json.get(i), Object.class);
return array;
}
public Object handleObject(JsonObject json, JsonDeserializationContext context) {
Map<String, Object> map = new HashMap<String, Object>();
for(Map.Entry<String, JsonElement> entry : json.entrySet())
//System.out.println(map.put(entry.getKey(), context.deserialize(entry.getValue(), Object.class)));
map.put(entry.getKey(), context.deserialize(entry.getValue(), Object.class));
//Log.i("Tango Inside Deserialize", "Tango Inside Deserialize");
return map;
}
@Override
public Object deserialize(JsonElement arg0,
java.lang.reflect.Type arg1,
JsonDeserializationContext arg2)
throws JsonParseException {
// TODO Auto-generated method stub.
return null;
}
}
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
Gson gson = gsonBuilder.create();
Object natural = gson.fromJson(line, Object.class);
//System.out.println(json);
System.out.println(natural);
Log.i("NaturalDeserializer", "NaturalDeserializer");
Java хэш, что я получаю:
{atoken=32ab3a8738a4b57165b5fc863af4f4c95198c2c9, utoken=9a3682e9eac186d56b230d075e7dc0d784992231}
Теперь мне нужно сделать вызов POST для:
curl --data "utoken=7d02a59410722737566f33879dcd061d5f45bc5a&lat=26.850307&lng=80.916853" http://www.website.com/khgt
За что мне нужно иметь значение utoken, я не знаю, как извлечь значение utoken. Может ли кто-нибудь помочь?
Кроме того, http://docs.oracle.com/javase/7/docs/api/java /util/Map.html#get(java.lang.Object) – ComputerDruid
Я добавил код. Не могли бы вы сейчас помочь? В документе говорится, что я должен использовать «V get (Object key)». Я попытался использовать его, но, напрасно. Не могли бы вы объяснить это в виде кода. Любая помощь будет высоко оценен. – user1903022