Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/204.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何反序列化可以是字符串、对象或列表的json/gson_Java_Android_Json_Gson - Fatal编程技术网

Java 如何反序列化可以是字符串、对象或列表的json/gson

Java 如何反序列化可以是字符串、对象或列表的json/gson,java,android,json,gson,Java,Android,Json,Gson,我有下面的json "notes": {"note": [ { "content": "Having wisdom teeth removed.", "from": "employee" }, { "content": "Get well soon", "from": "manager" } ]}, 问题是,该

我有下面的json

"notes": {"note": [
         {
             "content": "Having wisdom teeth removed.",
             "from": "employee"
         },
         {
             "content": "Get well soon",
             "from": "manager"
         }
     ]},
问题是,该值也可以

 "notes": "",

并将其储存在这些

public  class Notes
{
    @SerializedName ("note")
    public List<Note> note;
}
public  class Note
{
    @SerializedName ("content")
    public String content;
    @SerializedName ("from")
    public String from;
}
公共课堂笔记
{
@序列化名称(“注释”)
公开名单说明;
}
公开课堂讲稿
{
@序列化名称(“内容”)
公共字符串内容;
@SerializedName(“来自”)
来自的公共字符串;
}
我相信通过这样做,我解决了不是数组而是单个对象的问题

public class Json {
    private static Gson gson;

    private static class MyNoteClassTypeAdapter implements JsonDeserializer<List<RequestsDTO.Note>> {
        public List<RequestsDTO.Note> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
            List<RequestsDTO.Note> vals = new ArrayList<RequestsDTO.Note>();
            if (json.isJsonArray()) {
                for (JsonElement e : json.getAsJsonArray()) {
                    vals.add((RequestsDTO.Note) ctx.deserialize(e, RequestsDTO.Note.class));
                }
            } else if (json.isJsonObject()) {
                vals.add((RequestsDTO.Note) ctx.deserialize(json,RequestsDTO.Note.class));
            } else {
                throw new RuntimeException("Unexpected JSON type: " + json.getClass());
            }
            return vals;
        }
    }

    public static Gson getGson()
    {
        if (gson == null)
        {
            Type ListType = new TypeToken<List<RequestsDTO.Note>>() {}.getType();
            GsonBuilder builder = new GsonBuilder();
            builder.registerTypeAdapter(DateTime.class, new DateTimeSerializer());
            builder.registerTypeAdapter(ListType, new MyNoteClassTypeAdapter());
            gson = builder.create();
        }
        return gson;
    }
}
公共类Json{
专用静态Gson-Gson;
私有静态类MyNoteClassTypeAdapter实现JsonDeserializer{
公共列表反序列化(JsonElement json,类型typeOfT,JsonDeserializationContext ctx){
List vals=new ArrayList();
if(json.isJsonArray()){
for(JsonElement e:json.getAsJsonArray()){
add((RequestsDTO.Note)ctx.deserialize(e,RequestsDTO.Note.class));
}
}else if(json.isJsonObject()){
add((RequestsDTO.Note)ctx.deserialize(json,RequestsDTO.Note.class));
}否则{
抛出新的RuntimeException(“意外的JSON类型:+JSON.getClass());
}
返回VAL;
}
}
公共静态Gson getGson()
{
if(gson==null)
{
类型ListType=newTypeToken(){}.getType();
GsonBuilder=新的GsonBuilder();
registerTypeAdapter(DateTime.class,新的DateTimeSerializer());
registerTypeAdapter(ListType,新的MyNoteClassTypeAdapter());
gson=builder.create();
}
返回gson;
}
}

现在,当整个事情以字符串的形式返回时,我被卡住了……

想法是尝试将
“note”
字段(来自
“notes”
)作为
JSONArray
首先,如果它抛出异常,这将意味着
“note”
JSONArray
中没有
“notes”
JSONObject
这意味着
“注意”
JSONObject
。同样,当
note
字段是
String
时,我们可以计算出这种情况

try {
        //String jsonString="{\"notes\": {\"note\": [{\"content\": \"Having wisdom teeth removed.\",\"from\": \"employee\" }, {\"content\": \"Get well soon\", \"from\": \"manager\"} ] }}";
        //String jsonString="{\"notes\": { \"note\": {\"content\": \"This is a test note.\",\"from\": \"employee\"}}}";
        String jsonString="{\"notes\": { \"note\": \"\"}}";

        JSONObject jsonObject=new JSONObject(jsonString);
        JSONObject jsonObjectNotes=jsonObject.getJSONObject("notes");

        try{
            JSONArray jsonArrayNote=jsonObjectNotes.getJSONArray("note");
            for (int i = 0; i < jsonArrayNote.length(); i++) {

                JSONObject jsonObject2= jsonArrayNote.getJSONObject(i);
                String stringContent=jsonObject2.getString( "content");
                String stringFrom= jsonObject2.getString( "from");

                Log.e(getClass().getName(), "content="+stringContent +"; from="+stringFrom);
            }
        }
        catch(JSONException e){
            //that means that jsonObjectNotes has no jsonArray with name "notes" and "notes" is jsonObject
            try{
                JSONObject jsonObject3=jsonObjectNotes.getJSONObject("note");

                String stringContent=(String) jsonObject3.get( "content");
                String stringFrom=(String) jsonObject3.get( "from");

                Log.e(getClass().getName(), "content="+stringContent +"; from="+stringFrom);
            }
            catch(JSONException ex){
                //that means that jsonObjectNotes has no jsonObject with name "notes" and "notes" is empty String
                String stringNote=jsonObjectNotes.getString("note") ;       
                Log.e(getClass().getName(), "note is string ="+ stringNote);
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
试试看{
//String jsonString=“{\'notes\”:{\'note\”:[{\'content\”:\“正在拔掉智齿。\”,“\”来自\“:\”员工\“},{\'content\”:\“尽快康复”,\”来自\“:”经理\“}}”;
//字符串jsonString=“{\'notes\”:{\'note\”:{\'content\:\“这是一个测试注释。\”,\“from\”:“employee\”}};
字符串jsonString=“{\'notes\”:{\'note\”:\“\”}”;
JSONObject JSONObject=新的JSONObject(jsonString);
JSONObject jsonObjectNotes=JSONObject.getJSONObject(“notes”);
试一试{
JSONArray jsonArrayNote=jsonObjectNotes.getJSONArray(“note”);
for(int i=0;i

在我的示例代码中,另一个
get
操作也可以抛出jsonExceptions,但我想您已经明白了

看看Genson图书馆。 如果您的类是内部类,则将它们设置为静态。 下面的代码应该可以解决您的问题

Genson genson = new Genson.Builder().withDeserializerFactory(new NotesDeserializerFactory()).create();
Notes notes = genson.deserialize(in, Notes.class);

// Define a factory so you can delegate the deserialization to existing mechanisms for lists and beans
class NotesDeserializerFactory implements Factory<Deserializer<Notes>> {

    @Override
    public Deserializer<Notes> create(Type type, Genson genson) {
        Converter<List<Note>> noteListConverter = genson.provideConverter(new GenericType<List<Note>>() {}.getType());
        Converter<Note> noteConverter = genson.provideConverter(Note.class);
        return new NotesDeserializer(noteListConverter, noteConverter);
    }

}

// define an implementation for you Notes class so you can handle the different cases
class NotesDeserializer implements Deserializer<Notes> {
    private final Converter<List<Note>> noteListConverter;
    private final Converter<Note> noteConverter;

    public NotesDeserializer(Converter<List<Note>> noteListConverter,
            Converter<Note> noteConverter) {
        this.noteListConverter = noteListConverter;
        this.noteConverter = noteConverter;
    }

    @Override
    public Notes deserialize(ObjectReader reader, Context ctx) throws TransformationException,
            IOException {
        Notes notes = new Notes();
        if (reader.getValueType() == ValueType.ARRAY) notes.note = noteListConverter.deserialize(reader, ctx);
        else if (reader.getValueType() == ValueType.OBJECT) notes.note = Arrays.asList(noteConverter.deserialize(reader, ctx));
        else { // it is a litteral (string, numeric, boolean, null)
            notes.note = new ArrayList<Note>();
        }
        return notes;
    }
}
Genson Genson=new Genson.Builder().withDeserializerFactory(new notesdesserializerFactory()).create();
Notes=genson.deserialize(在Notes.class中);
//定义工厂,以便将反序列化委托给列表和bean的现有机制
类NotesDeserializerFactory实现工厂{
@凌驾
创建公共反序列化程序(类型,Genson-Genson){
Converter-noteListConverter=genson.ProviderConverter(新的GenericType(){}.getType());
Converter noteConverter=genson.provideConverter(注:等级);
返回新的NotesDeserializer(noteListConverter,noteConverter);
}
}
//为Notes类定义一个实现,以便处理不同的情况
类NotesDeserializer实现反序列化程序{
专用最终转换器;
专用最终转换器;
公共NotesDeserializer(转换器noteListConverter,
转换器(转换器){
this.noteListConverter=noteListConverter;
this.notecoverter=notecoverter;
}
@凌驾
public Notes反序列化(ObjectReader,Context ctx)引发TransformationException,
IOException{
注释=新注释();
if(reader.getValueType()==ValueType.ARRAY)notes.note=noteListConverter.deserialize(reader,ctx);
else if(reader.getValueType()==ValueType.OBJECT)notes.note=Arrays.asList(notecoverter.deserialize(reader,ctx));
else{//它是一个literal(字符串、数字、布尔值、null)
notes.note=新的ArrayList();
Genson genson = new Genson.Builder().withDeserializerFactory(new NotesDeserializerFactory()).create();
Notes notes = genson.deserialize(in, Notes.class);

// Define a factory so you can delegate the deserialization to existing mechanisms for lists and beans
class NotesDeserializerFactory implements Factory<Deserializer<Notes>> {

    @Override
    public Deserializer<Notes> create(Type type, Genson genson) {
        Converter<List<Note>> noteListConverter = genson.provideConverter(new GenericType<List<Note>>() {}.getType());
        Converter<Note> noteConverter = genson.provideConverter(Note.class);
        return new NotesDeserializer(noteListConverter, noteConverter);
    }

}

// define an implementation for you Notes class so you can handle the different cases
class NotesDeserializer implements Deserializer<Notes> {
    private final Converter<List<Note>> noteListConverter;
    private final Converter<Note> noteConverter;

    public NotesDeserializer(Converter<List<Note>> noteListConverter,
            Converter<Note> noteConverter) {
        this.noteListConverter = noteListConverter;
        this.noteConverter = noteConverter;
    }

    @Override
    public Notes deserialize(ObjectReader reader, Context ctx) throws TransformationException,
            IOException {
        Notes notes = new Notes();
        if (reader.getValueType() == ValueType.ARRAY) notes.note = noteListConverter.deserialize(reader, ctx);
        else if (reader.getValueType() == ValueType.OBJECT) notes.note = Arrays.asList(noteConverter.deserialize(reader, ctx));
        else { // it is a litteral (string, numeric, boolean, null)
            notes.note = new ArrayList<Note>();
        }
        return notes;
    }
}
String jsonStr = "your json string ";

Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();

JsonElement elem = jsonObj.get("note");

if(elem.isJsonArray()) { //**Array**
    List<Note> notelist = gson.fromJson(elem.toString(), new TypeToken<List<Note>>(){}.getType());
} else if(elem.isJsonObject()) { //**Object**
    Note note = gson.fromJson(elem.toString(), Note.class);
} else {  //**String**
    String note = elem.toString();
}