Is it possible to pass a JavaScript object from JavaScript to Java using addJavascriptInterface()? Something along these lines:
var javaScriptObject = {"field1":"string1", "field2":"string2"};
JavaScriptInterface.passObject(javaScriptObject);
How would such a call be captured on the Java side? I have no problem setting up the interface to send a string, but when I send an object, I receive null on the Java end.
AFAIK, addJavascriptInterface() only works with primitive types and Strings, and so you cannot pass arbitrary Javascript objects.
This is how I am doing...
In Android...
#JavascriptInterface
public void getJSONTData(String jsonData) {
try {
JSONObject data = new JSONObject(jsonData); //Convert from string to object, can also use JSONArray
} catch (Exception ex) {}
}
In JavaScript...
var obj = { Name : 'Tejasvi', Age: 100};
var str = JSON.stringify(obj);
Android.getJSONTData(str);
As of now, I could not find any other proper way to pass the native JavaScript object directly to JavascriptInterface.
Calling Android.getJSONTData({ Name : 'Tejasvi', Age: 100}) results in null (if parameter type is Object) or undefined (if parameter type is defined as String) in getJSONTData.
I found a solution, using JSON. My Java method returns a JSONArray, on my javascript code I receive this and convert to a javascript vector using JSON.parse(). See the example:
Java:
public class JavaScriptInterface {
Context mContext;
private static int ind=-1;
private static int [] val = { 25, 25, 50, 30, 40, 30, 30, 5, 9 };
public JavaScriptInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public JSONArray getChartData() {
String texto = " [ {name: 'valor1', 2007: "+val[(++ind)%9]+"}, "+
" {name: 'valor2', 2007: "+val[(++ind)%9]+"}, "+
" {name: 'valor3', 2007: "+val[(++ind)%9]+"} ]";
JSONArray jsonar=null;
try {
jsonar = new JSONArray(texto);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonar;
}
}
Now the javascript code:
window.generateData = function() {
/*var data = [ {name: 'valor1', 2007: 50},
{name: 'valor2', 2007: 20},
{name: 'valor3', 2007: 30} ]; */
var data = JSON.parse( Android.getChartData() );
return data;
};
The commented code above show how it was when static, and now the data came from the Java code.
It was testes on Android 2.1 and 3.2.
I can run this feature
In Javascript :
var data = {
'username' : $('#username').val().trim(),
'password' : $('#password').val().trim(),
'dns' : $('#dns').val().trim()
}
var str = JSON.stringify(data);
Native.getLoginService(str);
In Android :
#JavascriptInterface
public void getLoginService(String jsonData){
try{
JSONObject data = new JSONObject(jsonData);
String username = data.getString("username");
String password = data.getString("password");
String dns = data.getString("dns");
Log.i("TAG",username + " - " + password + " - " + dns);
}catch (Exception ex){
Log.i("TAG","error : " + ex);
}
}
Good luck with...
I think you can also pass JSONObject and JSONArray. So not only primitive types, but also primitive types stored in a javascript array [0,1,2] or dictionary {one:1, two:2}.
I have NOT verified this in code, just read the docs. Might be using it soon.
You can't pass JSONObject or JSONArray, but you can send strings with that form and parse them to those types.
Your option is to expose the method using strings and then you can use the JSONObject or JSONArray to parse the string and use it accordingly.
Here is what I did.
#JavascriptInterface
public void passJSON(String array, String jsonObj) throws JSONException
{
JSONArray myArray = new JSONArray(array);
JSONObject myObj = new JSONObject(jsonObj);
...
}
where array is '["string1","string2"]' and jsonObj is '{attr:1, attr2:"myName"}'
Related
Json1 {"key1" :"one","key2":"two"}
Json2 {"FN": "AB","LN":"XY"}
I wish to have Json3 {"key1" :"one","key2":"two","FN": "AB","LN":"XY"}
I have used below code but it does not work:
JSONObject mergedJSON = new JSONObject();
try {
mergedJSON = new JSONObject(json1, JSONObject.getNames(json1));
for (String Key : JSONObject.getNames(json2)) {
mergedJSON.put(Key, json2.get(Key));
}
} catch (JSONException e) {
throw new RuntimeException("JSON Exception" + e);
}
return mergedJSON;
}
* call defaultCOM {ID: "COM-123"}
* def defaultResponse = response.data.default
* def jMap = mergeJSON.toMap(defaultResponse)
Here error comes (language: Java, type: com.intuit.karate.graal.JsMap) to Java type 'org.json.JSONObject': Unsupported target type
All I'll say is that the recommended way to merge 2 JSONs is given in the documentation: https://github.com/karatelabs/karate#json-transforms
* def foo = { a: 1 }
* def bar = karate.merge(foo, { b: 2 })
* match bar == { a: 1, b: 2 }
I'll also say that when you use custom Java code, you should stick to using Map or List: https://github.com/karatelabs/karate#calling-java
And if you use things like JSONObject whatever that is, you are on your own - and please consider that not supported by Karate.
When you have to mix Java and the Karate-style JS code (and this something you should try to avoid as far as possible) you need to be aware of some caveats: https://github.com/karatelabs/karate/wiki/1.0-upgrade-guide#js-to-java
Well, if you just don't care about key collisions this should work:
String jsons01 = "{\"key1\" :\"one\",\"key2\":\"two\"}";
String jsons02 = "{\"FN\": \"AB\",\"LN\":\"XY\"}";
JSONObject jsono01 = new JSONObject(jsons01);
JSONObject jsono02 = new JSONObject(jsons02);
JSONObject merged = new JSONObject(jsono01, Object.getNames(jsono01));
for (String key : JSONObject.getNames(jsono02)) {
merged.append(key, jsono02.get(key));
}
System.out.println(merged);
Result is: {"key1":"one","FN":["AB"],"key2":"two","LN":["XY"]}
Trying to parse multi-level JSON in Java.
Having JSON input in format like this:
{"object1":["0","1", ..., "n"],
"objects2":{
"x1":{"name":"y1","type":"z1","values":[19,20,21,22,23,24]}
"x2":{"name":"y2","type":"z2","values":[19,20,21,22,23,24]}
"x3":{"name":"y3","type":"z1","values":[19,20,21,22,23,24]}
"x4":{"name":"y4","type":"z2","values":[19,20,21,22,23,24]}
}
and need to get all objects from 2 by one of the attributes, e.g. get all objects with type = z1.
Using org.json*.
Tried to do something like this:
JSONObject GeneralSettings = new JSONObject(sb.toString()); //receiving and converting JSON;
JSONObject GeneralObjects = GeneralSettings.getJSONObject("objects2");
JSONObject p2;
JSONArray ObjectsAll = new JSONArray();
ObjectsAll = GeneralObjects.toJSONArray(GeneralObjects.names());
for (int i=0; i < GeneralObjects.length(); i++){
p2 = ObjectsAll.getJSONObject(i);
switch (p2.getString("type")) {
case "z1": NewJSONArray1.put(p2); //JSON array that should contain values with type z1.
break;
case "z2": NewJSONArray2.put(p2); //JSON array that should contain values with type z2.
default: System.out.println("error");
break;
}
}
}
But getting null pointer exception and overall method seems not to be so well.
Please advise, is there any way to make it easier or, what am I doing wrong?
If you're getting a NullPointerException it's most likely that you haven't initialized NewJSONArray1 and NewJSONArray2.
You didn't include their declaration, but you probably just need to do
NewJSONArray1=new JSONArray();
NewJSONArray2=new JSONArray();
before your loop.
Aside: by convention java variables should start with a lower case letter, e.g. newJSONArray1
public static void main(String[] args) {
String s =
"{\"object1\":[\"0\",\"1\",\"n\"]," +
"\"objects2\":{" +
"\"x1\":{\"name\":\"y1\",\"type\":\"z1\",\"values\":[19,20,21,22,23,24]}," +
"\"x2\":{\"name\":\"y2\",\"type\":\"z2\",\"values\":[19,20,21,22,23,24]}," +
"\"x3\":{\"name\":\"y3\",\"type\":\"z1\",\"values\":[19,20,21,22,23,24]}," +
"\"x4\":{\"name\":\"y4\",\"type\":\"z2\",\"values\":[19,20,21,22,23,24]}" +
"}}";
System.out.println(s);
JSONObject json = new JSONObject(s);
JSONObject object2 = json.optJSONObject("objects2");
if (object2 == null) {
return;
}
JSONArray result = new JSONArray();
for (Object key : object2.keySet()) {
JSONObject object = object2.getJSONObject(key.toString());
String type = object.optString("type");
if ("z1".equals(type)) {
System.out.println(object.toString());
result.put(object);
}
}
System.out.println(result);
}
You can always convert it to string and use json-path:
https://code.google.com/p/json-path/
I expected to find this question around, but I couldn't. Maybe I'm Googling the wrong thing.
I have a primitive integer array (int[]), and I want to convert this into a String, that is "JSON-Parseable", to be converted back to the same int[].
What have I tried :
I tried this code :
// int[] image_ids_primitive = ...
JSONArray mJSONArray = new JSONArray(Arrays.asList(image_ids_primitive));
String jSONString = mJSONArray.toString();
Prefs.init(getApplicationContext());
Prefs.addStringProperty("active_project_image_ids", jSONString);
// Note: Prefs is a nice Class found in StackOverflow, that works properly.
When I printed the jSONString variable, it has the value : ["[I#40558d08"]
whereas, I expected a proper JSON String like this : {"1" : "424242" , "2":"434343"} not sure about the quotation marks, but you get the idea.
The reason I want to do this :
I want to keep track of local images (in drawable folder), so I store their id's in the int array, then I want to store this array, in the form of a JSON String, which will be later parsed by another activity. And I know I can achieve this with Intent extras. But I have to do it with SharedPreferences.
Thanks for any help!
You don't have to instantiate the JSONArray with Arrays.asList. It can take a normal primitive array.
Try JSONArray mJSONArray = new JSONArray(image_ids_primitive);
If you are using an API level below 19, one easy method would just be to loop over the int array and put them.
JSONArray mJSONArray = new JSONArray();
for(int value : image_ids_primitive)
{
mJSONArray.put(value);
}
Source: Android Developers doc
If you want a JSON array and not necessarily an object, you can use JSONArray.
Alternatively, for a quick hack:
System.out.println(java.util.Arrays.toString(new int[]{1,2,3,4,5,6,7}));
prints out
[1, 2, 3, 4, 5, 6, 7]
which is valid JSON. If you want anything more complicated than that, obviously JSONObject is your friend.
Try this way
int [] arr = {12131,234234,234234,234234,2342432};
JSONObject jsonObj = new JSONObject();
for (int i = 0; i < arr.length; i++) {
try {
jsonObj.put(""+(i+1), ""+arr[1]);
} catch (Exception e) {
}
}
System.out.println("JsonString : " + jsonObj.toString());
// If you wants the data in the format of array use JSONArray.
JSONArray jsonarray = new JSONArray();
//[1,2,1,] etc..
for (int i = 0; i < data.length; i++) {
jsonarray.put(data[i]);
}
System.out.println("Prints the Json Object data :"+jsonarray.toString());
JSONObject jsonObject=new JSONObject();
// If you want the data in key value pairs use json object.
// i.e {"1":"254"} etc..
for(int i=0;i<data.length;i++){
try {
jsonObject.put(""+i, data[i]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Prints the Json Object data :"+jsonObject.toString());
itertate this through the int array and you will get the json string
JSONStringer img = null ;
img = new JSONStringer() .object() .key("ObjectNAme")
.object() .key("something").value(yourIntarrayAtIndex0)
.key("something").value(yourIntarrayAtIndex1) .key("something").value(yourIntarrayAtIndex2)
.key("something").value(yourIntarrayAtIndex3)
.endObject() .endObject();
String se = img.toString();
Here se is your json string in string format
This code will achieve what you are after...
int index = 0;
final int[] array = { 100, 200, 203, 4578 };
final JSONObject jsonObject = new JSONObject();
try {
for (int i : array) {
jsonObject.put(String.valueOf(index), String.valueOf(i));
index++;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("YOUR_TAG", jsonObject.toString());
This will give you {"3" : "203", "2" : "200", "1": "100", "4": "4578"} as a string.
Not exactly sure why its not in the exact order, but sorting by a key is quite easy.
Alright. I have a JSON Object sent to me from a server which contains the following data:
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
}
The data I want to get is the status for the three status values. Data1, data2, and data3 always show up in that order, so I'm now trying to grab the data by index (e.g. data1 = index 0, data2 = index 1, data3 = index 2). How do I do that?
Try following:
String stat1;
String stat2;
String stat3;
JSONObject ret; //contains the original response
//Parse to get the value
try {
stat1 = ret.getJSONArray("results").getJSONObject(0).getString("status");
stat2 = ret.getJSONArray("results").getJSONObject(1).getString("status");
stat3 = ret.getJSONArray("results").getJSONObject(2).getString("status");
} catch (JSONException e1) {
e1.printStackTrace();
}
You would use JSONObject and JSONArray, the entire string is one JSONObject so you would construct one with it.
JSONObject object = new JSONObject(YOUR_STRING_OF_JSON);
Then you can access it with different get methods depending upon your expected type.
JSONArray results = object.getJSONArray("result"); // This is the node name.
String status = object.getString("status");
for (int i = 0; i < results.length(); i++) {
String resultStatus = results.getJSONObject(i).getString("status");
String type = results.getJSONObject(i).getString("type");
Log.w("JSON Result #" + i, "Status: " + resultStatus + " Type: " + type);
}
You need to surround it with a try/catch because JSON access can throw a JSONException.
Try re-factoring via a forEach loop
var testData =
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
};
var output = new Object;
var resultSet = new Object;
resultSet = testData.result;
resultSet.forEach(function(data)
{
theStatus = data['status'];
theType = data['type']
output[theType] = theStatus;
});
console.log( output['data1'] );
If you've got your models setup to mirror that data set, then you can let GSON (https://code.google.com/p/google-gson/) do a lot of your work for you.
If you want a bit more control, and want to parse the set yourself you can use JSONObject, JSONArray. There's an example of parsing and assembling a json string here: Android create a JSON array of JSON Objects
I am fairly new to JSON parser and I am trying to extract all data set from "sizes" tag i.e extracting values (small, yes, xsmall, NO, Medium and yes) from the JSON file in a complex nested loop but doesn't work. I am using GSON to parse the JSON file and using JAVA as programming language
Here how the JSON file looks like in general
{ response: "ok",
prodinfo: {
sizes: [
{ size:"small",
available: "yes"
},
{ size:"xsmall",
available: "No"
},
{ size:"Medium",
available: "yes"
}
]
}
}
This is what i did
int array = jsonParser14.parse(json14).getAsJsonObject().get("ProdInfo").getAsJsonObject().getAsJsonArray("sizes").size();
JsonArray sizes = (JsonArray) jsonParser15.parse(json15).getAsJsonObject().get("ProdInfo").getAsJsonObject().getAsJsonArray("sizes");
for (int i = 0; i <= array; i++) {
String size = sizes.get(i).getAsString();
System.out.println("data extracted are: " + size);
}
Your help will be appreciated.
Thanks
I usually treat this by making a public class with required fields :
public class ProdSize {
public String size;
public String available;
}
public class ProdInfo {
public ProdSize[] sizes;
}
public class Message {
public String response;
public ProdInfo prodinfo;
}
And then I just have to do this in gson :
Gson gson = new GsonBuilder().create();
Message mess = gson.fromJson(theJsonString, Message.class);
Then, I don't have any loop to do to parse the JSON. I directly have my sizes in
mess.prodinfo.sizes
For example you can print them like this
for (int i=0; i<mess.prodinfo.sizes.length; i++) {
ProdSize size = mess.prodinfo.sizes[i];
System.out.println("Size " + size.size + " -> " + size.available);
}
Something like:
var sizes = json.prodinfo.sizes;
for (item in sizes) {
if (sizes.hasOwnProperty(item)) {
var isAvailable = sizes[item].available;
alert(isAvailable);
}
}
Example here: http://jsfiddle.net/nG88B/3/
Edit:
Looks like you need to parse the JSON first. In which case (if it's valid) you can do:
var obj = JSON.parse(jsonStr);