gson在json中反序列化相同的键不同值

时间:2017-02-10 08:12:29

标签: java json

这是我的json活动

{  
  "type":"record",
  "name":"Doc",
  "doc":"adoc",
  "fields":[  
    {  
      "name":"id",
      "type":"string"
    },
    {  
      "name":"user_friends_count",
      "type":[  
        "int",
        "null"
      ]
    },
    {  
      "name":"user_location",
      "type":[  
        "string",
        "null"
      ]
    }}

要反序列化该事件,但仍然使用相同"type"个不同的值,例如一个"type" "string"值,另一个["string","null"]我怎样才能迭代它们?这是我的代码

import java.lang.reflect.Type;
import java.util.ArrayList;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
public class FieldaDeserialisation implements JsonDeserializer<Fields>{

public Fields deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
    JsonObject jobj = json.getAsJsonObject();
    JsonArray A1 = jobj.get("fields").getAsJsonArray();
    JsonPrimitive jtype = null;
    String jname = null;
    for (int i = 0; i < jobj.size(); i++) {
        JsonElement obj = A1.get(i);
        JsonObject b1 = obj.getAsJsonObject();
        jname = b1.get("name").getAsString();
        if (b1.get("type").isJsonArray()) {
            JsonArray jarray = b1.get("type").getAsJsonArray();
            for (int j = 0; j < jarray.size(); j++) {
                jtype = (JsonPrimitive) jarray.get(j); 
            }
        }
        else {
            jtype = (JsonPrimitive) b1.get("type");
        }
    }
}

它在同一行JsonArray A1 = jobj.get("fields").getAsJsonArray();和第1行import java.lang.reflect.Type;上显示错误

Exception in thread "main" java.lang.NullPointerException
    at FieldaDeserialisation.deserialize(FieldaDeserialisation.java:18)
    at FieldaDeserialisation.deserialize(FieldaDeserialisation.java:1)
    at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
    at com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:72)
    at com.google.gson.Gson.fromJson(Gson.java:887)
    at com.google.gson.Gson.fromJson(Gson.java:952)
    at com.google.gson.internal.bind.TreeTypeAdapter$GsonContextImpl.deserialize(TreeTypeAdapter.java:162)
    at JsonDataDeserialisation.deserialize(JsonDataDeserialisation.java:20)
    at JsonDataDeserialisation.deserialize(JsonDataDeserialisation.java:1)
    at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
    at com.google.gson.Gson.fromJson(Gson.java:887)
    at JsonMainClass.main(JsonMainClass.java:15)

这是我的主要反序列化课程

import java.lang.reflect.Type;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

public class JsonDataDeserialisation implements JsonDeserializer<JsonData>{

    @Override
    public JsonData deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        // TODO Auto-generated method stub
        JsonObject jobj = json.getAsJsonObject();
        String jsontype = jobj.get("type").getAsString();
        String jsonname = jobj.get("name").getAsString();
        String jsondoc = jobj.get("doc").getAsString();
        Fields[] fields = context.deserialize(jobj.get("fields"), Fields[].class);

        JsonData jdata = new JsonData();
        jdata.setType(jsontype);
        jdata.setName(jsonname);
        jdata.setDoc(jsondoc);
        jdata.setFields(fields);
        return jdata;
    }

}

这是主要的课程

import java.io.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;

public class JsonMainClass {
public static void main(String []args)throws Exception{
    String filepath = "/Users/RAGHU/Desktop/json1 .txt";
    GsonBuilder gsonb = new GsonBuilder();
    gsonb.registerTypeAdapter(JsonData.class, new JsonDataDeserialisation());
    gsonb.registerTypeAdapter(Fields.class, new FieldaDeserialisation());
    Gson gson = gsonb.create();
    try(JsonReader reader = new JsonReader(new FileReader(filepath))){
        reader.setLenient(true);
        JsonData jdata1 = gson.fromJson(reader, JsonData.class);
        System.out.println(jdata1);
    }
}
}

现在这是我以前做过的一个错误

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: This is not a JSON Array.
    at com.google.gson.Gson.fromJson(Gson.java:899)
    at com.google.gson.Gson.fromJson(Gson.java:952)
    at com.google.gson.internal.bind.TreeTypeAdapter$GsonContextImpl.deserialize(TreeTypeAdapter.java:162)
    at JsonDataDeserialisation.deserialize(JsonDataDeserialisation.java:20)
    at JsonDataDeserialisation.deserialize(JsonDataDeserialisation.java:1)
    at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
    at com.google.gson.Gson.fromJson(Gson.java:887)
    at JsonMainClass.main(JsonMainClass.java:15)
Caused by: java.lang.IllegalStateException: This is not a JSON Array.
    at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106)
    at FieldaDeserialisation.deserialize(FieldaDeserialisation.java:18)
    at FieldaDeserialisation.deserialize(FieldaDeserialisation.java:1)
    at com.google.gson.internal.bind.TreeTypeAdapter.read(TreeTypeAdapter.java:69)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
    at com.google.gson.internal.bind.ArrayTypeAdapter.read(ArrayTypeAdapter.java:72)
    at com.google.gson.Gson.fromJson(Gson.java:887)
    ... 7 more

1 个答案:

答案 0 :(得分:0)

调用

Fields[] fields = context.deserialize(jobj.get("fields"), Fields[].class);

您已经从此接收数组,只需将json解析为数组,然后迭代。

JsonArray A1 = json.getAsJsonArray();

然后你可以像你似乎那样进行迭代,使用type

类型的条件

为了更清洁,我会使用JsonElement来存储字段

JsonElement type = b1.get("type");
if(type.isJsonArray()){
    JsonArray array = type.getAsJsonArray();
    ...//ARRAY
else {
     String s = type.getAsString();
    ...//STRING
}