Lisa
Lisa

Reputation: 2999

How to decode JSON by using JSONObject.cs?

I am new to JSON and using the JSONObject.cs from the Unity Assets Store to decode the JSON file. I put the JSONObject.cs in the Standard Assets folder, the example.js is in Scripts folder. When I tested the example (in javascripts) in Unity:

  var encodedString: String = "{\"field1\": 0.5,\"field2\": \"sampletext\",\"field3\": [1,2,3]}";
  var j: JSONObject = new JSONObject(encodedString);

it has a compiler error, which is said:

BCE0024: The type 'JSONObject' does not have a visible constructor that matches the argument list '(String)'.

Do I need to declare the JSONObject class in example file again? Any thoughts would be very much appreciated!

Upvotes: 2

Views: 4284

Answers (2)

pjnovas
pjnovas

Reputation: 1126

After working 2 hours into this ... I have found the problem.

So, the C# class of JSONObject has a constructor (which you and me were using) with optional arguments. So as I understand from my tries calling it from Javascript won't work unless you send the optionals.

I have made it work by suppling the defaults on the call from JS.

This is the Contructor:

public JSONObject(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) {
    Parse(str, maxDepth, storeExcessLevels, strict);
}

Instead of calling from JS like this:

var obj: JSONObject = new JSONObject("{json here}");

Call it sending the same defaults that constructor have:

var obj: JSONObject = new JSONObject("{json here}", -2, false, false);

In that way you won't be using the defaults and it works (I know is agly, but I don't have time to do more work arounds... so here is the solution if some one got the same issue)

Upvotes: 2

user2886899
user2886899

Reputation: 16

Can you provide more info? The error you have says that you can't just add the string as a parameter to the constructor. Maybe you can just construct the JSonObject and then find a relevant method for decoding the Json string?

Upvotes: 0

Related Questions