在RealmDatabase中解析Json期间出现IllegalStateException

时间:2016-07-20 08:06:30

标签: java android realm realm-list

我使用数据库Realm,我有一个json对象,我需要从文件中解析并保存到数据库。

public class RealmString extends RealmObject{

    String string;

    public String getString() {
        return string;
    }

    public void setString(String string) {
        this.string = string;
    }
}

问题出现在对象pCommercialAccessRulle中,其中我们有一个字符串列表,不支持基元类型,这就是我创建对象的原因。

public class CommercialAccessRule extends RealmObject implements Serializable {


    private String tag;
    private RealmList<RealmString> contents;

    public CommercialAccessRule() {
    }

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }

    public RealmList<RealmString> getContents() {
        return contents;
    }

    public void setContents(RealmList<RealmString> contents) {
        this.contents = contents;
    }

}

在CommercialAccessRule类中,我创建的列表不是字符串,而是对象RealmString

Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING
at android.util.JsonReader.expect(JsonReader.java:310) at android.util.JsonReader.beginObject(JsonReader.java:293)
at io.realm.RealmStringRealmProxy.createUsingJsonStream(RealmStringRealmProxy.java:136) at io.realm.CommercialAccessRuleRealmProxy.createUsingJsonStream(CommercialAccessRuleRealmProxy.java:390) at io.re    
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRINGalm.PDataRealmProxy.createUsingJsonStream(PDataRealmProxy.java:525) at io.realm.DefaultRealmModuleMediator.createUsingJsonStream(DefaultRealmModuleMediator.java:257) at io.realm.Realm.createAllFromJson(Realm.java:435)

但是我收到了这样的错误

InputStream stream = null;
    try {
        stream = getApplicationContext().getAssets().open("test_pdata.json");
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        realm.beginTransaction();
        realm.createAllFromJson(PData.class, stream);
        realm.commitTransaction();
    } catch (IOException e) {
        realm.cancelTransaction();
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

搜索后我得到there然后there,但无法理解如何在此处实现它:

public class PData extends RealmObject implements Serializable{

    private static final String TAG = PData.class.getSimpleName();

    private String pName;
    private String pDesc;
    private boolean puoCompleted;
    private int pPID;
    private int pTotal;
    private int pOrder;
    private  int puoProgressCount;
    private int puoProgressPercent;
    private CommercialAccessRule pCommercialAccessRule;
    private String originalJson;

    public PData() {
    }


    public String getpName() {
        return pName;
    }

    public void setpName(String pName) {
        this.pName = pName;
    }

    public String getpDesc() {
        return pDesc;
    }

    public void setpDesc(String pDesc) {
        this.pDesc = pDesc;
    }

    public boolean ispuoCompleted() {
        return puoCompleted;
    }

    public void setpuoCompleted(boolean puoCompleted) {
        this.puoCompleted = puoCompleted;
    }

    public int getpPID() {
        return pPID;
    }

    public void setpPID(int pPID) {
        this.pPID = pPID;
    }

    public int getpTotal() {
        return pTotal;
    }

    public void setpTotal(int pTotal) {
        this.pTotal = pTotal;
    }

    public int getpOrder() {
        return pOrder;
    }

    public void setpOrder(int pOrder) {
        this.pOrder = pOrder;
    }

    public int getpuoProgressCount() {
        return puoProgressCount;
    }

    public void setpuoProgressCount(int puoProgressCount) {
        this.puoProgressCount = puoProgressCount;
    }

    public int getPuoProgressPercent() {
        return puoProgressPercent;
    }

    public void setPuoProgressPercent(int puoProgressPercent) {
        this.puoProgressPercent = puoProgressPercent;
    }

    public CommercialAccessRule getCommercialAccessRule() {
        return pCommercialAccessRule;
    }

    public void setpCommercialAccessRule(CommercialAccessRule pCommercialAccessRule) {
        this.pCommercialAccessRule = pCommercialAccessRule;
    }

    public String getOriginalJson() {
        return originalJson;
    }

    public void setOriginalJson(String originalJson) {
        this.originalJson = originalJson;
    }




    @Override
    public String toString() {
        return "PData{" +
                "pName='" + pName + '\'' +
                ", pDesc='" + pDesc + '\'' +
                ", puoCompleted=" + puoCompleted +
                ", pPID=" + pPID +
                ", pTotal=" + pTotal +
                ", pOrder=" + pOrder +
                ", puoProgressCount=" + puoProgressCount +
                ", puoProgressPercent=" + puoProgressPercent +
                ", pCommercialAccessRule=" + pCommercialAccessRule +
                ", originalJson='" + originalJson + '\'' +
                '}';
    }

}

这是我在上面写的类PDate,json。

news/news/*

2 个答案:

答案 0 :(得分:0)

按照以下步骤操作:

  1. 获得JsonResponse后,通过调用方法&#34; toMap(your_jsonResponse_object)&#34;将响应对象作为参数传递给JsonHelper类。

  2. JsonHelper类将JsonObject转换为map。

  3. map包含键值(它也可能包含arraylist),根据键获得值。
  4. 4.使用您获得的值更新您的领域对象。

    //对不起我的错误解释。

    //使用此类可以转换json数据

    https://gist.github.com/codebutler/2339666

    复制
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.util.*;
    
    public class JsonHelper {
    public static Object toJSON(Object object) throws JSONException {
        if (object instanceof Map) {
            JSONObject json = new JSONObject();
            Map map = (Map) object;
            for (Object key : map.keySet()) {
                json.put(key.toString(), toJSON(map.get(key)));
            }
            return json;
        } else if (object instanceof Iterable) {
            JSONArray json = new JSONArray();
            for (Object value : ((Iterable)object)) {
                json.put(value);
            }
            return json;
        } else {
            return object;
        }
    }
    
    public static boolean isEmptyObject(JSONObject object) {
        return object.names() == null;
    }
    
    public static Map<String, Object> getMap(JSONObject object, String key) throws JSONException {
        return toMap(object.getJSONObject(key));
    }
    
    public static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap();
        Iterator keys = object.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            map.put(key, fromJson(object.get(key)));
        }
        return map;
    }
    
    public static List toList(JSONArray array) throws JSONException {
        List list = new ArrayList();
        for (int i = 0; i < array.length(); i++) {
            list.add(fromJson(array.get(i)));
        }
        return list;
    }
    
    private static Object fromJson(Object json) throws JSONException {
        if (json == JSONObject.NULL) {
            return null;
        } else if (json instanceof JSONObject) {
            return toMap((JSONObject) json);
        } else if (json instanceof JSONArray) {
            return toList((JSONArray) json);
        } else {
            return json;
         }
      }
    }
    

    //在活动中将jsonObject传递给上面的类,你将得到Map / Arraylist

    public class MainActivity extends AppCompatActivity {
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
       Map<String,Object> convertedData = new HashMap<>();
       // pass the jsonResponse to JsonHelperClass
        convertedData = toMap(jsonObject);
    
        //upadte your realm object
        your_realm_object.updateWithJsonData(convertedData);
    
         }
     }
    
     //realmObject class
    public YourRealm extends RealmObject{
    
     String name;
     String id;
     String desc;
    // setters and getters
    
    //update realm Object with json data
     public void updateWithJsonData(Map<String,Object> data){
    
      setName(data.get("pName"));
      setId(data.get("pPID"));
      //......
      }
    }
    

答案 1 :(得分:0)

如果要为元素创建JSON对象,请使用GSON。为此。

Fox ex:

RealmObject obj  = new RealmObject();
obj.setpPID(1);
obj.setpName("myName");
obj.setpDesc(myDescription");
obj.setpTotal(120);
obj.setpOrder(1);
obj.setpuoCompleted(false);
obj.setpuoProgressPercent(0);
obj.setpuoProgressCount(0);
CommercialAccessRule innerobj = new CommercialAccessRule();
innerobj.setTag("myTag");
List<String> strList = new ArrayList<>();
strList.add("string object");
strList.add("string object");
obj.setpCommercialAccessRule(innerobj);
Gson gson = new Gson();
String JSONString = gson.toJson(obj);
RealmObject obj1 = gson.fromJson(JSONString,RealmObject.class);

JSONString的结果将是

{ “PPID”:1, “PNAME”: “MYNAME”, “pDesc”: “myDescription”, “PTOTAL”:120, “pOrder”:1, “puoCompleted”:假 “puoProgressPercent”:0, “puoProgressCount”:0,“pCommercialAccessRule”:{“tag”:“myTag”,“contents”:[“string object”,“string object”]}}

使用它来验证你的jSON:https://jsonformatter.curiousconcept.com/