0

I want to get the list of properties' names from a given JSON string in Kotlin.

Example JSON string:

val jsonString = """
        {
            "id": 2,
            "title": "iPhone X",
            "description": "SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...",
            "price": 899,
            "discountPercentage": 17.94,
            "rating": 4.44,
            "stock": 34,
            "brand": "Apple",
            "category": "smartphones",
            "thumbnail": "https://i.dummyjson.com/data/products/2/thumbnail.jpg",
            "images": [
                "https://i.dummyjson.com/data/products/2/1.jpg",
                "https://i.dummyjson.com/data/products/2/2.jpg",
                "https://i.dummyjson.com/data/products/2/3.jpg",
                "https://i.dummyjson.com/data/products/2/thumbnail.jpg"
            ]
        }
    """

Output:

[id, title, description, price, discountPercentage, rating, stock, brand, category, thumbnail, images] 
Abdullah Almasud
  • 159
  • 1
  • 11
  • 1
    Does this answer your question? [How to parse JSON in Kotlin?](https://stackoverflow.com/questions/41928803/how-to-parse-json-in-kotlin) – InSync Jul 28 '23 at 17:23
  • No, That is not the answer to the question you mentioned. I asked to get the only properties' names from a given JSON object string @InSync – Abdullah Almasud Jul 28 '23 at 18:42

1 Answers1

-1

To get the solution of the problem we need to use Regular expression (RegEx) to find all the properties' names from the JSON strings.

val pattern = """"\w+":""".toRegex()
val output = pattern.findAll(jsonString)
val properties = output.toList().map {property -> property.value.replace("\"", "").replace(":", "")}
println(properties)
Abdullah Almasud
  • 159
  • 1
  • 11
  • Downvoted because using regex to parse JSON is asking for trouble. See https://stackoverflow.com/a/8751940/611819 – dnault Jul 28 '23 at 17:53
  • I asked to get the only properties' names from a given JSON object string, not parse JSON @dnault – Abdullah Almasud Jul 28 '23 at 18:46
  • Have you tested with the full range of valid property names? What about `foo"bar`, `foo\"bar`, `foo@bar`, `foobar`, `foo bar`, `foo\u0023bar` and so on. A JSON parser will handle all of these and more. – dnault Jul 28 '23 at 19:39