Convert String to JsonObject in kotlin returns null

20,444

Solution 1

Since you are running your code with Junit, it running on the SDK on your computer. This SDK doesn't provide everything, some are just some skeleton class providing signature of method and documentation but not the code. So you can't execute directly.

Try to add the library in testing

testImplementation 'org.json:json:your_version'

See the version here :

http://mvnrepository.com/artifact/org.json/json

This is based on the answer on this post: JSONObject returns a non null value of "null" after instantiating with string

Solution 2

I run this funtion to parse your string and it's ok. Your string is valid. Can you specify how do you init val content

 fun parseJson() {
    var stringJson = "{\"sessions\": [{\"locations\": [{\"lat\": \"14.2294625\",\"lng\": \"121.1509005\",\"time\": 1560262643000,\"speed\": 0,\"speedLimit\": 0},{\"lat\": \"14.2294576\",\"lng\": \"121.1509498\",\"time\": 1560262713000,\"speed\": 0,\"speedLimit\": 0},{\"lat\": \"14.2294576\",\"lng\": \"121.1509498\",\"time\": 1560262714000,\"speed\": 0,\"speedLimit\": 0}],\"name\": \"1.5645220491E12\"}  ]}"

    var obj = JSONObject(stringJson)
    System.out.println("obj1: $obj")
    var sessionArray: JSONArray = obj.optJSONArray("sessions")
    System.out.println("obj1: $sessionArray")
    var firstObject = sessionArray[0]
    System.out.println("obj1: $firstObject")
}

Solution 3

  1. There is no need to substring your JSON string. Put it inside JSONObject and it will work fine.
  2. If you need to get neasted objects use getJSONObject or getJSONArray methods
  3. Show your content string in code (or how do you load it)

Your edited code

val content = "the string above"

var obj = JSONObject(content)
Share:
20,444
Marlon
Author by

Marlon

Android Developer I want to collaborate and make an impact on the things I work on. I have a passion for programming. Driven problem solver. I am detail oriented and have good communication skills. View my apps here: https://play.google.com/store/apps/developer?id=Rapid+Developers [email protected]

Updated on July 09, 2022

Comments

  • Marlon
    Marlon almost 2 years

    Edit Found Solution:

    Found the error in my code. I'm running this on a unit test and Android doesn't use JSON objects on unit tests because it's part of android. That's why it was returning null.

    Question:

    I'm tying to convert my String back to a JsonObject using JSONObject("string")

    Here is a sample of my String:

    {
      "sessions": [
        {
          "locations": [
            {
              "lat": "14.2294625",
              "lng": "121.1509005",
              "time": 1560262643000,
              "speed": 0,
              "speedLimit": 0
            },
            {
              "lat": "14.2294576",
              "lng": "121.1509498",
              "time": 1560262713000,
              "speed": 0,
              "speedLimit": 0
            },
            {
              "lat": "14.2294576",
              "lng": "121.1509498",
              "time": 1560262714000,
              "speed": 0,
              "speedLimit": 0
            }
          ],
          "name": "1.5645220491E12"
        }
      ]
    }
    

    Its returning null on my JsonObjects:

    content = "the string above"
    
    var obj = JSONObject(content.substring(content.indexOf("{"), content.lastIndexOf("}") + 1))
    System.out.println("obj1: " + obj.toString())
    
    obj = JSONObject(content)
    System.out.println("obj1: " + obj.toString())
    
    var obj1 = JSONArray(content)
    System.out.println("obj1: " + obj1.toString())
    
    obj1 = JSONArray(content.substring(content.indexOf("{"), content.lastIndexOf("}") + 1))
    System.out.println("obj2: " + obj1.toString())
    

    All the outputs of this are null. Any way to know what error happens so I can adjust my json string?

    • Sergei Mikhailovskii
      Sergei Mikhailovskii almost 5 years
      maybe it's better to create a pojo model and use Gson library? Or you don't have such opportunity?
    • Nikola C
      Nikola C almost 5 years
      Try using Retroft, it is much faster and easier.
    • Marlon
      Marlon almost 5 years
      @SergeiMikhailovskii this is just a simple unit test reading from a local json text file. Yes that is possible but I want to know why this code is not working.
  • Marlon
    Marlon almost 5 years
    Already did that, you can see in my code I have tried many different ways to convert it to an object, all of them return null.
  • Marat Zangiev
    Marat Zangiev almost 5 years
    Show how you load your string