【问题标题】:IllegalStateException during the parsing of Json in RealmDatabaseRealmDatabase 解析 Json 时出现 IllegalStateException
【发布时间】:2016-07-20 08:06:29
【问题描述】:

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

  {
    "pPID": 1,
    "pName": "myName",
    "pDesc": "myDescription",
    "pTotal": 120,
    "pOrder": 1,
    "puoCompleted": false,
    "puoProgressPercent":0,
    "puoProgressCount":0,
    "pCommercialAccessRule": {
      "tag": "myTag",
      "contents": [
        "string object", "string object"
      ]
    }
  }

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

public class RealmString extends RealmObject{

    String string;

    public String getString() {
        return string;
    }

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

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

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;
    }

}

但我收到这样的错误

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)

搜索后我得到there,然后是there,但在这里无法理解如何实现:

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();
            }
        }
    }

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

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 + '\'' +
                '}';
    }

}

【问题讨论】:

标签: java android realm realm-list


【解决方案1】:

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

狐狸前任:

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":false,"puoProgressPercent":0, "puoProgressCount":0,"pCommercialAccessRule":{"tag":"myTag","contents":["string object","string object"]}}

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

【讨论】:

    【解决方案2】:

    按照以下步骤操作:

    1. 获取 JsonResponse 后,通过调用方法“toMap(your_jsonResponse_object)”将响应对象作为参数传递给 JsonHelper 类。

    2. JsonHelper 类将 JsonObject 转换为地图。

    3. map 包含键值(也可能包含arraylist),根据键您将获得值。

    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;
         }
      }
    }
    

    //在activity中将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"));
      //......
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-14
      • 1970-01-01
      • 2013-01-23
      • 2018-04-25
      • 1970-01-01
      • 2018-08-11
      • 2018-08-24
      • 2016-01-16
      • 1970-01-01
      相关资源
      最近更新 更多