wiliam
wiliam

Reputation: 19

Represent file structure to JSON

I want to represent current files structure in JSON or XML code but with some conditions.

For example: for this structure

my_project
├── feature1
│   └── src
│       └── java
│           └── com
│               └── directory
│                   ├── MainActivity.kt
│                   └── MainFragment.kt
└── feature2
    └── src
        └── java
            └── com
                └── directory
                    ├── Feature2Activity.kt
                    └── Feature2Fragment.kt

Should generate

{
  "my_project": {
    "feature1": {
      "directory": ["MainActivity"]
    },
    "feature2": {
      "directory": ["Feature2Activity"]
    }
  }
}

It doesn't matter if I can't do this at runtime, think of it as a script that I will use on directory. Not at runtime of the App.

Upvotes: 1

Views: 318

Answers (1)

Animesh Sahu
Animesh Sahu

Reputation: 8096

The source files are compiled into JVM bytecode and then they are compiled into the Dex (Dalvik Executable) that can run on the Android platform.

You can use the Dex file of your application that can be accessed by the context.

val activityFiles = mutableListOf<String>()

DexFile(context.getPackageCodePath()).entries().apply {
    while(hasMoreElement()) {
        val fileName = nextElement.substringAfterLast('.').substringBefore('$')
        if(fileName.contains("Activity")) activityFiles.add(fileName)
    }
}

// Logic to generate Json. You may use any json library.
val innerJson = mutableMapOf(
    getAppName() to mapOf(
        "directory" to activityFiles
    )
)

// Hard-code the parent project name (holding both sub application)
val jsonRepresentation: MutableMap<String, Any> = mutableMapOf("my_project" to innerJson)

val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()

val json = moshi.adapter(Map::class.java).toJson(jsonRepresentation)


fun getAppName(ctx: Context) {
    val appInfo = context.getApplicationInfo()
    val id = appInfo.labelRes
    return if (id == 0) applicationInfo.nonLocalizedLabel.toString()
    else context.getString(id)
}

I wonder if there it is possible to have feature1 info and feature2 both, as you will be having context of that specified application. If you are writing code in feature1 then won't be able to see classes / app name of the other feature2.

References

Upvotes: 1

Related Questions