Results 1 to 5 of 5
  1. #1
    mdehghani is offline Member
    Join Date
    Jan 2017
    Rep Power

    Default String Json to Map?

    hi everyone!
    i'm trying to convert a string json read from remote url (including integers and doubles) to Map using the Gson library but It appears that i always receieve a null.
    the string jason is :

    [{"Month":136901,"CPI":2.4},{"Month":136902,"CPI":2 .4}]

    and my code is:

    String json = jsonString; //mentioned above
    Gson gson = new Gson();
    Map<Integer, Double> map = new HashMap<Integer, Double>();
    map = (Map<Integer, Double>)gson.fromJson(json, map.getClass());
    Last edited by mdehghani; 01-10-2017 at 08:08 PM.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Northern Virginia, United States
    Rep Power

    Default Re: String Json to Map?

    I am not familiar with the json library API but it looks to me like the map should be Map<String, Double>. Nor do I understand how the library constructs the map since Month and CPI occur twice but a Map must have unique keys for all values.

    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    jameswarner is offline Member
    Join Date
    Mar 2016
    9345 Cemetery Dr. Scarsdale
    Rep Power

    Default Re: String Json to Map?

    You can convert JSON string to java map object using Jackson's data binding. If you need example please check reference code link How to convert JSON string to Map? - Jackson JSON examples

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Voorschoten, the Netherlands
    Blog Entries
    Rep Power

    Default Re: String Json to Map?

    The outer JSON object is an array [ ... ] and it contains two objects { ... }' the outer object cannot be converted to a HashMap (or whatever Map).

    kind regards,

    Build a wall around Donald Trump; I'll pay for it.

  5. #5
    gozzy is offline Member
    Join Date
    Jan 2017
    Rep Power

    Default Re: String Json to Map?

    Looks like you'd be better of with an array or List of some object that models the json

Similar Threads

  1. Convert JSON string to HashMap in Java
    By anjibman in forum New To Java
    Replies: 9
    Last Post: 09-12-2014, 09:14 AM
  2. Write POJO for JSON string
    By anjibman in forum New To Java
    Replies: 1
    Last Post: 08-21-2014, 04:49 PM
  3. Replies: 8
    Last Post: 11-12-2010, 03:00 PM
  4. Json
    By mac in forum New To Java
    Replies: 10
    Last Post: 06-08-2010, 11:15 PM
  5. JSON Lib: json-lib-1.0-jdk13.jar
    By Raghuraman K in forum Advanced Java
    Replies: 3
    Last Post: 05-13-2010, 10:00 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts