java - GSON: Cannot correctly parse JSON object -


i trying parse json object following gson:

{  "key1":"somevalue",  "key2":{                "anotherkey1":"212586425",             "anotherkey2":"martin"          } } 

this code:

data data = new gson().fromjson(json, data.class); 

here data class:

public class data {          public string key1;         public map key2; //this break everything. } 

what expect (i new gson) produces value of key2 map object.

however, error expected begin_object string makes me think passing string, should passing json object.

isn't gson parsing whole json string pass in beginning? eventually, new data source map object. feasible ?

let gson work. defined data as

package stackoverflow.questions.q19228349;  public class data {      @override     public string tostring() {         return "data [key1=" + key1 + ", key2=" + key2 + "]";     }     public string key1;     public object key2;  } 

and can parse both cases key2:

package stackoverflow.questions.q19228349;  import com.google.gson.gson;  public class q19228349 {       public static void main(string[] args){     string json =             "{\"key1\":\"somevalue\","+             "\"key2\":{   "+             "           \"anotherkey1\":\"212586425\","+             "           \"anotherkey2\":\"martin\""+             "        }"+             " }";      string json2 =             "{\"key1\":\"somevalue\","+             "\"key2\":\"astring\""+             " }";          gson g = new gson();         data d = g.fromjson(json, data.class);          system.out.println("first: " +d);          data d2 = g.fromjson(json2, data.class);          system.out.println("second: "+d2);     }   } 

this result:

first: data [key1=somevalue, key2={anotherkey1=212586425, anotherkey2=martin}] second: data [key1=somevalue, key2=astring]


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -