简体   繁体   中英

Converting a simple JSON string to object

I have this class:

public class MyClass {
    public int number;
    public long date;
}

I have a JSON string that I'm converting to a MyClass object by doing:

String s = "{\"Number\":2,\"Date\":1444953600}";
MyClass temp = new Gson().fromJson(s, MyClass.class);

However, I'm getting the following exception:

Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $

at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:387)

at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:210)

What am I doing wrong?

EDIT

As requested, this is the complete code:

URL url = new URL(some_url);
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("GET");

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer response = new StringBuffer();

String inputLine;
while ((inputLine = reader.readLine()) != null) {
    response.append(inputLine);
}
reader.close();

MyClass temp = new Gson().fromJson(response.toString(), MyClass.class);

And the update class is:

public class MyClass implements Serializable {
    @SerializedName("Number")
    public int number;

    @SerializedName("Date")
    public long date;
}

Use annotation @SerializedName, like:

public class MyClass {
    @SerializedName("Number")
    public int number;
    @SerializedName("Date")
    public long date;
}
String s = "{\"number\":2,\"date\":1444953600}";
tp temp = new Gson().fromJson(s, tp.class);

chack upper and lower case of variable names

You need to do something like this: (Assuming that you're actually going to need to do it for multiple entries.)

public class MyClass{
     public int number;
     public long date;

     MyClass(int num, long Date){
          this.number = num;
          this.date = Date;
     }
}

Then in your other class, to convert into an object:

ArrayList<MyClass> list = new ArrayList<>();
list.add(new MyClass(string1, string2));

With: (Will possibly need to be surrounded by try&catch)

JSONObject Object = new JSONObject(s); // Where s is your string.
String string1 = new String(Object.getString("Number"));
String string2 = new String(Object.getString("Date"));

Hope this helps, it might be slightly more complicated than you need but it means that it's scalable.

try without the capital letters :

String s = "{\"number\":2,\"date\":1444953600}";

edit: i tried this like that:

import com.google.gson.Gson;

public class App {
public static void main(String[] args) {
    String s = "{number:2,date:1444953600}";
    MyClass temp = new Gson().fromJson(s, MyClass.class);
    System.out.println("number="+temp.number+" , "+temp.date);
}

class MyClass {
    public int number;
    public long date;
}
}

and it works

Try this -

ElemntList.java

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class ElemntList {
    @SerializedName("Number")
    @Expose
    private Integer Number;
    @SerializedName("Date")
    @Expose
    private Long Date;

    public Integer getNumber() {
        return Number;
    }

    public void setNumber(Integer Number) {
        this.Number = Number;
    }

    public Long getDate() {
        return Date;
    }

    public void setDate(Long Date) {
        this.Date = Date;
    }

    @Override
    public String toString() {
        return "ElemntList [Number=" + Number + ", Date=" + Date + "]";
    }

}

Main.java

import com.example.ElemntList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Main {
    private static Gson gson;

    static {
        gson = new GsonBuilder().create();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        String s = "{\"Number\":2,\"Date\":1444953600}";
        ElemntList info = gson.fromJson(s, ElemntList.class);
        System.out.println(info);
   }
}

Result

ElemntList [Number=2, Date=1444953600]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM