JSON解析器与对象崩溃

时间:2015-06-10 09:59:46

标签: java android json

下一个代码接收基于inputStream的JSON阅读器。当我尝试解析String或Int时,它工作正常。但是,当我有一个对象时,例如,其属性为firstName和lastName字符串的对象Name,解析器效果不佳。 JSON代码具有以下形式:

{
"name": {
"firstName": "Mikel",
"lastName": "Corcu"
}
}

我使用的代码是下一个,它在我执行reader.nextName()时崩溃,意图在Name之后获取下一个String,在这种情况下firstName和lastName:

public User formatUser(JsonReader reader) throws IOException {

    User usuario = new User();
    reader.beginObject();
    while (reader.hasNext()) {
        String user = reader.nextName();
        System.out.println("El objeto es:"+user);
        switch (user) { 
            case "name":
                Name nombre = new Name();
                reader.nextName(); // CRASH HERE
                nombre.setFirstName(reader.nextString());

                reader.nextName();
                nombre.setLastName(reader.nextString());

                usuario.setName(nombre);
                System.out.println("Nombre: "+usuario.getName().getFirstName());

                reader.skipValue();
                break;
            case "gender":
                usuario.setGender(reader.nextString());
                System.out.println("Genero: "+usuario.getGender());
                reader.skipValue();
                break;
            case "birthDate":
                /*Date birthDate =new Date();
                birthDate = stringToDate(reader.nextString());
                usuario.setBirthDate((java.sql.Date) birthDate);*/
                reader.skipValue();
                break;
            case "friendCount":
                usuario.setFriendCount(reader.nextInt());
                System.out.println("Numero de amigos: "+usuario.getFriendCount());
                reader.skipValue();
            default:
                reader.skipValue();
                break;
        }
    }
    reader.endObject();

    return usuario;
}

logcat是下一个:

06-10 11:53:47.857: E/ServicioRest(12504): Error!
06-10 11:53:47.857: E/ServicioRest(12504): java.lang.IllegalStateException: Expected a name but was BEGIN_OBJECT at line 38 column 13 path $.name
06-10 11:53:47.857: E/ServicioRest(12504):  at com.google.gson.stream.JsonReader.nextName(JsonReader.java:800)
06-10 11:53:47.857: E/ServicioRest(12504):  at com.hc.parsers.UserParser.formatUser(UserParser.java:47)
06-10 11:53:47.857: E/ServicioRest(12504):  at com.hc.parsers.UserParser.leerUser(UserParser.java:32)
06-10 11:53:47.857: E/ServicioRest(12504):  at com.hc.parsers.UserParser.readJsonStream(UserParser.java:23)
06-10 11:53:47.857: E/ServicioRest(12504):  at com.hc.modelo.ObtencionDatosUsuario.doInBackground(ObtencionDatosUsuario.java:48)
06-10 11:53:47.857: E/ServicioRest(12504):  at com.hc.modelo.ObtencionDatosUsuario.doInBackground(ObtencionDatosUsuario.java:1)
06-10 11:53:47.857: E/ServicioRest(12504):  at android.os.AsyncTask$2.call(AsyncTask.java:288)
06-10 11:53:47.857: E/ServicioRest(12504):  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
06-10 11:53:47.857: E/ServicioRest(12504):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
06-10 11:53:47.857: E/ServicioRest(12504):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-10 11:53:47.857: E/ServicioRest(12504):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-10 11:53:47.857: E/ServicioRest(12504):  at java.lang.Thread.run(Thread.java:818)

我没有正确理解"期待一个名字,但是BEGIN_OBJECT"。非常感谢。

编辑1:这是完整的解析器类:

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;

import com.google.gson.stream.JsonReader;
import com.holacampus.api.domain.Name;
import com.holacampus.api.domain.User;

public class UserParser {

public User readJsonStream(InputStream in) throws IOException {
    // Nueva instancia JsonReader
    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    try {
        // Leer Array
        return leerUser(reader);
    } finally {
        reader.close();
    }

}
public User leerUser(JsonReader reader) throws IOException {
    // Lista temporal 
    User user = new User();
    user = formatUser(reader);

    return user;
}

public User formatUser(JsonReader reader) throws IOException {

    User usuario = new User();
    reader.beginObject();
    while (reader.hasNext()) {
        String user = reader.nextName();
        System.out.println("El objeto es:"+user);
        switch (user) { //Cuando intenta parsear no encuentra estos case y entonces devuelve a null el usuario.
            case "name":
                Name nombre = new Name();
                reader.nextName(); // CRASH HERE
                nombre.setFirstName(reader.nextString());

                reader.nextName();
                nombre.setLastName(reader.nextString());

                usuario.setName(nombre);
                System.out.println("Nombre: "+usuario.getName().getFirstName());

                reader.skipValue();
                break;
            case "gender":
                usuario.setGender(reader.nextString());
                System.out.println("Genero: "+usuario.getGender());
                reader.skipValue();
                break;
            case "birthDate":
                /*Date birthDate =new Date();
                birthDate = stringToDate(reader.nextString());
                usuario.setBirthDate((java.sql.Date) birthDate);*/
                reader.skipValue();
                break;
            case "friendCount":
                usuario.setFriendCount(reader.nextInt());
                System.out.println("Numero de amigos: "+usuario.getFriendCount());
                reader.skipValue();
            default:
                reader.skipValue();
                break;
        }
    }
    reader.endObject();

    return usuario;
}

@SuppressLint("SimpleDateFormat")
public Date stringToDate(String fecha){
    SimpleDateFormat formato = new SimpleDateFormat("dd-mm-yyyy");
    Date date= new Date();
    try {
        date = formato.parse(fecha);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return date;
}

}

2 个答案:

答案 0 :(得分:0)

JSONObject jMainObject;
String firstName, lastName;
jMainObject = new JSONObject("Your Server Response");

if(jMainObject.has("Name")){
    JSONObject jDataObject = jMainObject.getJSONObject("Name");
    firstName = jDataObject.getString("firstName");
    lastName = jDataObject.getString("lastName");
}else{
    firstName = jMainObject.getString("firstName");
    lastName = jMainObject.getString("lastName");
}

Log.i("Name", firstName+" - "+lastName);

完成

答案 1 :(得分:0)

这里name是一个JSONObject而不是一个简单的JSON字段,这就是它抛出这个错误的原因。 只需修改代码就像JSONObject一样解析它:

case "name":

reader.beginObject(); //this indicates name a JSONObject
reader.nextName(); 
nombre.setFirstName(reader.nextString());