Reputation: 11188
My Json String is look like this:
{
"Status": "Success",
"ErrorText": "",
"GetMySizeResult": {
"Chest": "43",
"Shoulder": "33",
"NeckFront": "32",
"NeckBack": "2",
"Waist": "3",
"Abdomen": "3",
"Hip": "4",
"Length": "4",
"SlitLength": "4",
"ArmHole": "4",
"SleeveLengthShort": "4",
"SleeveLengthLong": "4",
"SleeveRoundShort": "",
"SleeveRoundLong": "",
"WaistToAnkle": "",
"Thigh": "",
"Knee": "",
"Calf": "",
"Ankle": "",
"Instruction": "",
"Note": ""
}
}
My coding is below:
@SuppressWarnings("unchecked")
public static <T> T JsonParseforReturnModel(T t, String response)
throws JsonSyntaxException, IOException, XmlPullParserException {
InputStream in = new ByteArrayInputStream(response.getBytes());
JsonReader reader;
reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
Gson gson = new Gson();
reader.beginObject();
reader.nextName();
reader.nextString();
reader.nextName();
reader.nextString();
reader.nextName();
reader.beginObject();
t = (T) gson.fromJson(reader, t.getClass());
reader.close();
return t;
}
but it contains error:
Expected BEGIN_OBJECT but was NAME at line 1 column 61
please solve my error.Thanks in advance.sorry for my bad english.
Upvotes: 0
Views: 2489
Reputation: 20406
Try to remove reader.beginObject()
before calling gson.fromJson()
. It looks gson.fromJson()
expects begin_object tag but it has being already consumed.
Upvotes: 4
Reputation: 18522
I know this isn't necessarily the answer your looking for, but I find that the easiest and most maintainable way to use Gson is to define a class for the object, then use gson to unpack to that class.
i.e.
public class PersonSizesMessage{
public String status;
public String error;
public PersonSizes personSizes;
}
public class PersonSizes{
int Chest;
int Shoulder;
// and all the rest...
}
PersonSizesMessage msg = gson.fromJson(jsonString, PersonSizesMessage.class);
See the "BagOfPrimitives" example in the docs.
Upvotes: 1