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!
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)
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?
Related
I want to build a method to dynamically save attributes on a specific object
given the attribute name and the value to save I call the "save()" function to update the global targetObj
var targetObj = targetClass();
save(String attribute, String value){
targetObj.attribute = value;
print(targetObj.attribute);
}
But I'm getting the following error:
Class 'targetClass' has no instance setter 'attribute='.
Receiver: Instance of 'targetClass'
Tried calling: attribute="Foo"
The only thing that I can think of is that "attribute" due to being type String results in an error.
That lead me to think if there is a way to read a String as code, something like eval for php.
As #Randal mentioned, you cannot create class..method at runtime. Still, you can try something like this.
A certain class
class Foo {
dynamic bar1;
dynamic bar2;
// ...
}
Your save method
save(Foo fooObject, String attribute, dynamic value) {
if ("bar1" == attribute) fooObject.bar1 = value;
else if ("bar2" == attribute) fooObject.bar2 == value;
// ...
}
Dart (and thus flutter) does not have a way to compile and execute code at runtime (other than dart:mirrors, which is deprecated). You can build additional code that derives from other code using the various builder mechanisms, although it can be rather complicated to implement (and use!).
Now I'm using UIEventListener to add a clicker.When I write it in one file, it works all right.like this:
UIEventListener.Get(popButton).onClick = showPop;
But when I wrote it to two seprate files it gives me error.first file:
public class Adapter{
var grid:GameObject;
function addItems(data:List.<PrintItem>, prefab:GameObject, func:Function){
for(var i:int=0;i<data.Count;i++){
var gameObject:GameObject = NGUITools.AddChild(grid, prefab);
UIEventListener.Get(gameObject).onClick = func;
}
}
}
second file:
//I use the funtion like this
adapter.addItems(list, GO[0], hidePop);
//the hidePop is like this
var hidePop:Function = function(){
switchPopMenu(false);
};
when I run the unity give me the error
InvalidCastException: Cannot cast from source type to destination type.
Adapter.addItems (System.Collections.Generic.List`1 data,
UnityEngine.GameObject prefab, ICallable func) (at
Assets/Scripts/yhj/Tools/Adapter.js:12)
try using EventDelegate.Add(obj.onClick, func);. Direct assignment may cause certain issues.
I am using dotnetrdf and trying to parse some triples with NTriplesParser. I have my own handler RobHandler in which I process each triple in turn.
public class RobHandler : BaseRdfHandler
{
protected override bool HandleTripleInternal(Triple t)
{
string predicateUrl = ((BaseUriNode)(t.Predicate)).Uri.AbsoluteUri;
string value = t.Object.ToString();
}
}
This works fine but I want to get the object minus the language. My objects look like "Lincoln"#en. I could obviously write some code to remove the #en bit, but I'd rather use some library code rather than my own that hard-coded strings like #en. To do this I think I need to create a LiteralNode but there doesn't seem to be a way to get from a string which is what I have (my variable value) to a LiteralNode.
How can I extract just the textual value from an object string?
Actually I think I have the answer myself:
if (t.Object.NodeType == NodeType.Literal)
{
var node = (ILiteralNode)t.Object;
}
Running a Play! app with Scala. I'm doing a request where the response is expected to be a JSON string. When checking the debugger, the JsonElement returns OK with all information as expected. However, the problem is when I try to actually run methods on that JsonElement.
val json = WS.url("http://maps.googleapis.com/maps/api/geocode/json?callback=?&sensor=true&address=%s", startAddress+","+startCity+","+startProvince).get.getJson
val geocoder = json.getAsString
The only error I get back is Unsupported Operation Exception: null and I've tried this on getAsString and getAsJsonObject and getAsJsonPrimitive
Any idea why it's failing on all methods? Thanks.
I had a similar problem and I had to change jsonObject.getAsString() to jsonObject.toString();
Maybe your JsonElement is a JsonNull
What you could do is to first check that it isn't by using json.isJsonNull
Otherwise, try to get its String representation with json.toString
In my case I just needed to get the element as an empty string if it is null, so I wrote a function like this:
private String getNullAsEmptyString(JsonElement jsonElement) {
return jsonElement.isJsonNull() ? "" : jsonElement.getAsString();
}
So instead of
val geocoder = json.getAsString
You can just use this
val geocoder = getNullAsEmptyString(json);
It returns "" if the element is null and the actual string if it is not
To add to #Henry's answer. In the spirit of Kotlins "OrNull" Adding an extension function:
fun JsonElement.asStringOrNull(): String? {
return if (isJsonNull) null else asString
}
The class JsonElement will throw Unsupported Operation Exception for any getAs<Type> method, because it's an abstract class and makes sense that it is implemented in this way.
For some reason the class JsonObject, does not implement the getAs<Type> methods, so any call to one of these methods will throw an exception.
Calling the toString method on a JsonElement object, may solve your issue in certain circumstances, but isn't probably what you want because it returns the json representation as String (e.g. \"value\") in some cases.
I found out that also a JsonPrimitive class exists and it does implement the getAs<Type> methods. So probably the correct way to proceed is something like this:
String input = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
JsonParser parser = new JsonParser();
JsonElement jsonTree = parser.parse(input);
if(jsonTree != null && jsonTree.isJsonObject()) {
JsonObject jsonObject = jsonTree.getAsJsonObject();
value = jsonObject.get("key1").getAsJsonPrimitive().getAsString()
}
PS. I removed all the nullability mgmt part. If you are coding in Java you probably want to manage this in a better way.
see GitHub source code for JsonElement:
https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/JsonElement.java#L178
I am using the following code in GWT client
Inside my jsni method I am using the following code, Assume that typeName is String argument
typeName = '$wnd.mysample.SampleButton'
var sample = new window[typeName]();
sample.addButton(name, parent);
SampleButton implements Exportable class, I used #ExportPackage("mysample") and #Export(all = true).
In My entry module I called ExporterUtil.exportAll();
Note: if I replace
var sample = new $wnd.mysample.SampleButton() with new window[typeName]() then it is working fine otherwise it is throwing undefined function called.
Kindly let me know how to create an instance for the type in JSNI code
eval('var sample = $wnd.mysample.SampleButton();'); solves the issue.