Android: Issue using JSON library in pure java package

rayano :

Our Android app has a package that consists of only pure Java code that is decoupled from Android. I need to use JSON in this package, and tried importing the official JSON library. Whilst the import is successful, and I can use JSON in code, it refuses to work. I constantly get the same exception:

java.lang.NoSuchMethodError: No static method g(Ljava/lang/String;)Ljava/lang/Object; in class Lorg/json/JSONObject; or its super classes (declaration of 'org.json.JSONObject' appears in /system/framework/core-libart.jar)

No virtual method b()Z in class Lorg/json/JSONObject; or its super classes (declaration of 'org.json.JSONObject' appears in /system/framework/core-libart.jar)

I have no idea why I'm getting this. I've read around that this is due to a conflict with Android's included JSON library but this is only being used in the pure Java library and any code interaction with Android involves strings or longs, not JSON

Has anyone ever experienced this? Or have any suggestions as to how I can use JSON in this pure java package?

I've tried importing a very old version of the JSON library incase it is due to some kind of conflict where I am using newer methods, but no dice. Same error. Also tried importing the jar instead of using gradle.

This is used for simple getter and setters for a database in ORMLITE. Here is one example where mExtraFlag is a string. Methods that also cause issues are toString from JSONObject and also the methods: valueToString, StringToValue etc...

public JSONObject getExtraFlag() {
 return new JSONObject(mExtraFlag);
}
rayano :

For anyone who ever experiences the same issue, this is my hack fix. I decided to use gson

Again, I have to emphasize that this is for a DECOUPLED JAVA PACKAGE. If you are attempting to import the JSON library in a regular Android package, this is probably not the solution for you. Actually, the other answer might apply to you then.

Gradle:

dependencies {
    implementation 'com.google.code.gson:gson:2.8.5'
}

Maven:

<dependencies>
<!--  Gson: Java to Json conversion -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.5</version>
      <scope>compile</scope>
    </dependency>
</dependencies>

Example parsing to json object and from a string

public JsonObject toJson(String value) {
    return new JsonParser().parse(value).getAsJsonObject();
}

// (probably dosen't require a method)
public String fromJson(JsonObject json) {
    return json.toString();
}

How to create and insert into a JSON object:

JsonObject object = new JsonObject();
object.addProperty(key, value);

Example getting a long value (mExtraFlag is a string)

toJson(mExtraFlag).get(key).getAsLong();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=135656&siteId=1