1

Key convert into jsonobject using org.json.simple. I have tried a number of ways to did it but all failed

1st way

JSONObject name1 = (JSONObject) jsonObject.get(key);

error : cannot convert java.lang.string to org.json.simple.json.object

2nd way

JSONParser parser = new JSONParser();
JSONObject name1 = (JSONObject) parser.parse(key);

error : Unexpected character (N) at position 0. at org.json.simple.parser.Yylex.yylex(Unknown Source) at org.json.simple.parser.JSONParser.nextToken(Unknown Source) at org.json.simple.parser.JSONParser.parse(Unknown Source) at org.json.simple.parser.JSONParser.parse(Unknown Source) at org.json.simple.parser.JSONParser.parse(Unknown Source)

3rd way

Long name1 = Long.valueOf(jsonObject.get(key));

error: The method valueOf(String) in the type Long is not applicable for the arguments (Object)

4th way

I used this function:

optJSONObject(key)

error: optJSONObject is undefined for JSONObject

How can I get this to work?

theduck
  • 2,589
  • 13
  • 17
  • 23
Danish
  • 257
  • 2
  • 12
  • What exactly is the `key` string? Can you show us the value that `key` holds? – Troley Nov 17 '19 at 10:22
  • ``` JSONObject json = new JSONObject(); // get the keys of json object Set keys = obj.keySet(); Iterator iterator = keys.iterator(); //Iterator iterator = obj.keys(); String key = null; while (iterator.hasNext()) { key = (String) iterator.next();``` – Danish Nov 17 '19 at 10:35
  • in key every iteration can come string , JSONObject , JSONArray – Danish Nov 17 '19 at 10:36

2 Answers2

1

So the JSONObject.get(key) function usually doesn't return a json object itself. But the org.json packet hast accounted for this. Careful reading from this point since org.json includes 2 JSONObject packages, the org.json.simple and the plain org.json.JSONObject and thus I don't know if this explicitly works in org.json.simple but it's what I do when handling JSONObjects with the org.json package.

JSONObject name1 = jsonObject.getJSONObject(key);

This line does what you want to do there. Try it.

The JSON package brings functions like getInt, getString, getJSONObject for you to specify exactly what type of data you want to get.

Sepx3
  • 38
  • 10
  • sir i tried this library org.json but by this i got error in parsing because in parsing i used org.json.simple.. then error came org.json.simple cannot parse into org.json ``` Object obj = parser.parse(new FileReader("C:/Users/Envy/Documents/company.json")); JSONObject jsonObject = (JSONObject) obj;``` – Danish Nov 17 '19 at 10:42
  • ```JSONObject jsonObject = (JSONObject) obj; JSONObject name1 = jsonObject.getJSONObject(key);``` the method getJSONObject(String) is undefined for the type JSONObject – Danish Nov 17 '19 at 10:53
  • This is because you defined your JSONObject to be extracted from the library org.json.simple.JSONObject and not org.json.JSONObject. It's a very unclear thing but if you check your references and change them to org.json.JSONObject across the boards you should be fine with this method – Sepx3 Nov 17 '19 at 11:07
  • ```JSONParser parser = new JSONParser();``` this is undefined in org.json.JSONObject.. how i do it ...using org.json.JSONObject. – Danish Nov 17 '19 at 11:41
  • So what does the JSONParser do for you, I couldn't really find anything about it – Sepx3 Nov 17 '19 at 12:46
  • 1
    Please check the link where it shows how to transform from one class to another using jackson and same can be used to transform the json string to other classes - https://www.thetechnojournals.com/2019/10/entity-object-conversion-to-dto-object.html – Ashok Prajapati Nov 17 '19 at 13:43
  • brother i did successfully but why updation value of key is not reflect in my JSON file .. – Danish Nov 17 '19 at 14:32
0

This line

error : Unexpected character (N) at position 0.

in your 2nd way code fragment / quote kind of states that you're parsing invalid JSON. JSONObject name1 = (JSONObject) parser.parse(key); the key in this line probably contains invalid JSON. That is why the parser throws an exception.

You can try to debug the code and see what the key strings look like and you should find out which one (if not all) contain invalid JSON.

I created a minimalistic program which parses a valid JSONArray (or a JSONObject, if the file contains only a single JSON object) from a file (which you mentioned under @Sepx3's answer). I tried to use names from your code snippets for the relevant code, so that it stays a bit clear.

The content of my C:/Users/Envy/Documents/company.json example file:

[
  {
    "key": "value"
  },
  {
    "key1": "value1"
  },
  [
    {
      "key2": "value2"
    },
    {
      "key3": "value3"
    }
  ]
]

And the code which parses it, stores it into the object and then checks whether a JSONArray or a single JSONObject has been parsed (in my example it is a JSONArray).

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.io.FileReader;

public class DemoApplication {

    public static void main(String[] args) {
        JSONParser parser = new JSONParser();

        Object obj = null;
        try {

            obj = parser.parse(new FileReader("C:/Users/Envy/Documents/company.json"));

        } catch (Exception e) {
            // Handle possible exceptions
            e.printStackTrace();
        }

        // If the parsed string was a single json object
        if (obj instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) obj;

            // Do something with jsonObject, in this example it prints the content of jsonObject
            System.out.println(jsonObject);

        }
        // Or else if the parsed string was a json array
        else if (obj instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) obj;

            // Do something with jsonArray, in this example it prints the content of jsonArray
            System.out.println(jsonArray);
        }
    }
}

I hope this helps you at least a bit and sets you on the right track.

Troley
  • 1,421
  • 1
  • 12
  • 14