首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何反序列化可以是字符串、对象或列表的json/gson

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

Stack Overflow用户
提问于 2012-11-08 12:17:19
回答 3查看 6.9K关注 0票数 3

我有以下json

代码语言:javascript
运行
复制
"notes": {"note": [
         {
             "content": "Having wisdom teeth removed.",
             "from": "employee"
         },
         {
             "content": "Get well soon",
             "from": "manager"
         }
     ]},

问题是,价值也可以是

代码语言:javascript
运行
复制
 "notes": "",

代码语言:javascript
运行
复制
"notes": {"note": {
            "content": "This is a test note.",
            "from": "employee"
        }},

并将其存储在这些

代码语言:javascript
运行
复制
public  class Notes
{
    @SerializedName ("note")
    public List<Note> note;
}
public  class Note
{
    @SerializedName ("content")
    public String content;
    @SerializedName ("from")
    public String from;
}

通过这样做,我相信我解决了不是数组而是单个对象的问题

代码语言:javascript
运行
复制
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;
    }
}

而现在,当整个事情变成一个字符串时,我被困住了……

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-11-08 14:04:41

这个想法是首先尝试将"note"字段(来自"notes" JSONObject)作为JSONArray,如果它抛出异常,这将意味着没有"note" JSONArray"notes" JSONObject中,这将意味着"note"是D9。当note字段为String时,我们可以用同样的方法来解决这种情况。

代码语言:javascript
运行
复制
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();
    }

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

票数 1
EN

Stack Overflow用户

发布于 2014-01-31 19:46:54

参考下面的代码片段,使用Gson库无一例外地反序列化您的json。

代码语言:javascript
运行
复制
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();
}
票数 2
EN

Stack Overflow用户

发布于 2012-11-08 18:05:57

看看Genson库http://code.google.com/p/genson/。如果您的类是内部类,则将其设置为静态类。下面的代码应该可以解决您的问题。

代码语言:javascript
运行
复制
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;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13282308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档