JSON.kt 1.64 KB
Newer Older
Jonas Waeber's avatar
Jonas Waeber committed
1
2
package org.memobase.helpers

3
import ch.memobase.rdf.NS
Jonas Waeber's avatar
Jonas Waeber committed
4
5
6
import com.beust.klaxon.JsonArray
import com.beust.klaxon.JsonObject
import com.beust.klaxon.Klaxon
7
import com.beust.klaxon.KlaxonException
Jonas Waeber's avatar
Jonas Waeber committed
8
import java.io.StringReader
9
import org.apache.logging.log4j.LogManager
Jonas Waeber's avatar
Jonas Waeber committed
10
11
12

object JSON {

13
14
    private val log = LogManager.getLogger("JsonParser")

15
16
17
18
19
20
21
22
23
24
25
26
    private const val graph = "@graph"
    private const val atId = "@id"
    const val atType = "@type" // rdf:type
    const val type = "type" // rico:type
    private const val Record = "Record"
    private const val RecordSet = "RecordSet"
    private const val CorporateBody = "CorporateBody"
    private const val memobaseInstitution = "memobaseInstitution"
    const val institution = "institution"
    const val record = "record"
    const val recordSet = "recordSet"

Jonas Waeber's avatar
Jonas Waeber committed
27
28
    private val klaxon = Klaxon()

29
30
31
32
33
34
35
    fun parse(data: String): JsonObject {
        return try {
            klaxon.parseJsonObject(StringReader(data))
        } catch (ex: KlaxonException) {
            log.error("${ex.localizedMessage} -> $data.")
            JsonObject()
        }
Jonas Waeber's avatar
Jonas Waeber committed
36
37
38
    }

    fun unpack(input: JsonObject): Map<String, JsonObject> {
39
        val graph = input[graph] as JsonArray<JsonObject>
Jonas Waeber's avatar
Jonas Waeber committed
40
        return graph.map {
41
42
43
44
45
46
            if (it[atType] == NS.rico + Record) {
                Pair(record, it)
            } else if (it[atType] == NS.rico + RecordSet) {
                Pair(record, it)
            } else if (it[atType] == NS.rico + CorporateBody && it[type] == memobaseInstitution) {
                Pair(institution, it)
Jonas Waeber's avatar
Jonas Waeber committed
47
            } else {
48
                Pair(it[atId] as String, it)
Jonas Waeber's avatar
Jonas Waeber committed
49
50
51
52
53
54
            }
        }.toMap()
    }


}