1

Please do not mark it as duplicate, I went through many of those related posts, but in vain. I am new to Android/ Java programming and need help in knowing how to convert json map to a java hashmap. Please refer the code below:

HttpPost httpPost1 = new HttpPost(
                        "http://www.mywebsite.com/something.json" );
                Log.i("MAP", "Hash call");
                List<NameValuePair> nameValuePair1 = new ArrayList<NameValuePair>(1);
                nameValuePair1.add(new BasicNameValuePair("id_token", token ));

                    try {
                        httpPost1.setEntity(new UrlEncodedFormEntity(nameValuePair1));
                    } catch (UnsupportedEncodingException e) {
                        // writing error to Log
                        e.printStackTrace();
                    }

                    // Making HTTP Request
                    try {
                    HttpResponse response1 = httpClient.execute(httpPost1);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response1.getEntity().getContent(), "UTF-8"));
                   StringBuilder builder = new StringBuilder();
                   for (line = null; (line = reader.readLine()) != null;) {
                      // builder.append(line).append("\n");

                       System.out.println(line);
                     Log.i("Line1", "line1 "+ line);

                 class Data {
                   private Email email;
                   private String result;
                   // Add/generate getters and setters.

                   class Email {
                       private List<Alert> alerts;
                       private String session;
                       // Add/generate getters and setters.
                   }

                   class Alert {
                       private Long AlertID;
                       private String tim;
                       private String lng;
                       private String lat;

                       }
               }

             Gson gson=new Gson(); 
             String json="{\"AlertID\":\"tim\",\"lng\",\"lat\"}";
             Map<String,String> map=new HashMap<String,String>();
            java.lang.reflect.Type type = new TypeToken<Map<String, String>>(){}.getType();
            Map<String, String> myMap = gson.fromJson("{\"AlertID\":\"tim\",\"lng\",\"lat\"}", type);
             System.out.println(json);
            Log.i("JAVA Hash", "Java Hash call");
                   }//Closing for loop//line


                   JSONTokener tokener = new JSONTokener(builder.toString());
                   JSONArray finalResult = new JSONArray(tokener);
                        // writing response to log
                    Log.i("Http Response:", response1.toString());
                    Log.i("JSON returns: ", "JSON returns");
                    } catch (ClientProtocolException e) {
                        // writing exception to log
                        e.printStackTrace();
                    } catch (IOException e) {
                        // writing exception to log
                        e.printStackTrace();

                    }

The json which needs to be converted to hashmap is as follows:

 {\"myemailid@gmail.com\":\"lat\":0.0,\"lng\":0.0,\"tim\":"2014-10-02T10:38:11.437Z"},{"lat":0.0,"lng":0.0,"tim":"2014-10-02T08:56:38.459Z"},{"lat":0.0,"lng":0.0,"tim":"2014-10-02T08:47:18.713Z"},{"lat":0.0,"lng":0.0,"tim":"2014-10-02T08:43:58.145Z"},{"lat":0.0,"lng":0.0,"tim":"2014-10-02T08:34:08.798Z"}]}

Just to make the json more readable:

myemailid@gmail.com

lat : 0 lng : 0 tim : "2014-10-01T16:55:15.002Z"

lat : 0 lng : 0 tim : "2014-10-01T16:18:07.290Z"

lat : 0 lng : 0 tim : "2014-10-01T12:04:06.364Z"

lat : 0 lng : 0 tim : "2014-10-01T11:58:04.455Z"

lat : 0 lng : 0 tim : "2014-10-01T11:46:24.560Z"

Any help in this regard would be highly appreciated.

user1903022
  • 1,075
  • 1
  • 13
  • 19

2 Answers2

1

Have you tried to put " around your numeric values?

{"email":"myemailid@gmail.com",
 "items":[{"lat":"0.0","lng":"0.0","tim":"2014-10-02T08:56:38.459Z"},
          {"lat":"0.0","lng":"0.0","tim":"2014-10-02T08:47:18.713Z"},
          {"lat":"0.0","lng":"0.0","tim":"2014-10-02T08:43:58.145Z"},
          {"lat":"0.0","lng":"0.0","tim":"2014-10-02T08:34:08.798Z"},
          {"lat":"0.0","lng":"0.0","tim":"2014-10-02T08:28:21.437Z"}]}

Had once an issue with missing quotations marks .... no longer 100% sure, if it was related to gson or genson.

added: note added "email" and "items" above as well

Gson gson = new GsonBuilder().create();
ResultJson result = gson.fromJson(jsonStringAsShownAbove, ResultJson.class); 

class ResultJson {
    private String email;
    private List<TimeAndLocation> items = new ArrayList<TimeAndLocation>();
}

class TimeAndLocation {
    private double lat;
    private double lon;
    private String tim;
}
Trinimon
  • 13,839
  • 9
  • 44
  • 60
  • I tried, but it didn't help. Could you suggest how exactly should I convert the json given into a java hash? – user1903022 Oct 02 '14 at 11:25
  • I think the code looks somehow as shown above. Note my updates on the JSON structure. I'd expect some issues if your first identifier is an email address so I changed it to `"email"` . – Trinimon Oct 02 '14 at 13:30
0

The reason you are getting this Exception because you are not using the JSON which you have posted in the question.

Instead you are using the JSON:

{\"AlertID\":\"tim\",\"lng\",\"lat\"}

which you have used in the following line in your code:

 Map<String, String> myMap = gson.fromJson("{\"AlertID\":\"tim\",\"lng\",\"lat\"}", type);

The above JSON is obviously a malformed JSON, since the attribute lng has no value corresponding to it, which a valid JSON must have. So, ideally your JSON should be something like:

{\"AlertID\":\"tim\",\"lng\":0.0,\"lat\":0.0}

Try using the actual well formed JSON and your problem should be solved.

Rahul Bobhate
  • 4,892
  • 3
  • 25
  • 48
  • I tried as per your instruction, but, got something like this: {"AlertID":"tim","lng":0.0,"lat":0.0} I need to store the entire json as a java hash, so that, I may access it whenever I may need it. The entire json looks like: JSON myemailid@gmail.com 0 lat : 0 lng : 0 tim : "2014-10-01T16:55:15.002Z" 1 lat : 0 lng : 0 tim : "2014-10-01T16:18:07.290Z" 2 lat : 0 lng : 0 tim : "2014-10-01T12:04:06.364Z" 3 lat : 0 lng : 0 tim : "2014-10-01T11:58:04.455Z" 4 lat : 0 lng : 0 tim : "2014-10-01T11:46:24.560Z" Please let me know how can I convert it into java hash. Thanks a lot. – user1903022 Oct 02 '14 at 11:20
  • Updated. Please suggest further. – user1903022 Oct 02 '14 at 11:48
  • What exactly is the `myemailid@gmail.com`. I'm assuming that it is the key whose value is the array of `Alert`. Also, post the JSON in a valid format. – Rahul Bobhate Oct 02 '14 at 11:53
  • I am making a POST call to a website which returns a json hash(as posted in the question) containing email id as the key and an array of 5 last coordinates (latest first) as elements for that key. I need to store it as a java hash now. The exact json that is being returned from website is: {"myemailid@gmail.com":[{"lat":0.0,"lng":0.0,"tim":"2014-10-01T16:55:15.002Z"},{"lat":0.0,"lng":0.0,"tim":"2014-10-01T16:18:07.290Z"},{"lat":0.0,"lng":0.0,"tim":"2014-10-01T12:04:06.364Z"},{"lat":0.0,"lng":0.0,"tim":"2014-10-01T11:58:04.455Z"},{"lat":0.0,"lng":0.0,"tim":"2014-10-01T11:46:24.560Z"}]} – user1903022 Oct 02 '14 at 12:00
  • Is the key always going to be `myemailid@gmail.com` ? Or could it be any different? – Rahul Bobhate Oct 02 '14 at 12:03
  • The key would always be an "email id" of a person using this application. – user1903022 Oct 02 '14 at 12:22
  • You'll need to write a custom deserializer for that. You should take a look at this question: http://stackoverflow.com/questions/6096940/how-do-i-write-a-custom-json-deserializer-for-gson – Rahul Bobhate Oct 02 '14 at 12:39