Daniël van den Berg
Daniël van den Berg

Reputation: 2355

Don't use android's built in org.json

I've written a library that uses org.json (A) from json.org, under the assumption that Android used the same (in android it's also called org.json (B), just that it misses some relatively critical features). Now what I'd like to do is set up my gradle, so that my project uses org.json (A) instead of org.json (B). I've tried adding the following to my app.gradle:

android {
    blabla
    defaultConfig {
        blabla
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets{
        main{
            java{
                exclude 'org/json/**'
            }
        }
    }

}

However, this does not seem to work. I still have Android's org.json (B) available to me, and when typing new JSONObject() it still uses Android's implementation. How could I fix this?

Upvotes: 4

Views: 1827

Answers (2)

sealor
sealor

Reputation: 155

You can relocate your org.json dependency to another package name. This can be done with the gradle shadow plugin.

Plugin project: https://github.com/johnrengelman/shadow
Plugin documentation: https://imperceptiblethoughts.com/shadow/

My working example:
Hint: I'm using a java library project "lib" within my Android project which has a dependency to org.json.

lib/build.gradle

apply plugin: 'java-library'
apply plugin: 'com.github.johnrengelman.shadow'

buildscript {
    repositories {
        maven {
            url "https://plugins.gradle.org/m2/"
        }
    }
    dependencies {
        classpath 'com.github.jengelman.gradle.plugins:shadow:4.0.3'
    }
}

shadowJar {
    relocate 'org.json', 'shadow.org.json'
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation('org.json:json:20180813')
}

sourceCompatibility = "1.7"
targetCompatibility = "1.7"

app/build.gradle

apply plugin: 'com.android.application'

android {
    [..]
}

dependencies {
    [..]
    implementation project(path: ':lib', configuration: 'shadow')
}

Upvotes: 3

CommonsWare
CommonsWare

Reputation: 1006614

How could I fix this?

Change yours from org.json to org.something.else. You cannot replace system-supplied packages with ones from an app, even for your own process. You do not control the runtime classpath, and the firmware always wins.

Or, switch from org.json to something that performs better, such as Gson or Jackson.

Upvotes: 3

Related Questions