get key name & key value from json - java

I'm totally new to java. How do I get the key name & key value of this jsonobject & pass it to my increment method?
args = {'property_name':1}
private boolean handlePeopleIncrement(JSONArray args, final CallbackContext cbCtx) {
JSONObject json_array = args.optJSONObject(0);
mixpanel.getPeople().increment(key_name, key_value);
cbCtx.success();
return true;
}
UPDATE
Now I'm getting the error:
Object cannot be converted to Number
Number value = json_array.get(key);
-
private boolean handlePeopleIncrement(JSONArray args, final CallbackContext cbCtx) {
JSONObject json_array = args.optJSONObject(0);
Iterator<?> keys = json_array.keys();
while( keys.hasNext() ) {
String key = (String) keys.next();
Number value = json_array.get(key);
// System.out.println("Key: " + key);
// System.out.println("Value: " + json_array.get(key));
}
mixpanel.getPeople().increment(key, value);
cbCtx.success();
return true;
}

Try using this
JSONObject json_array = args.optJSONObject(0);
Iterator<?> keys = json_array.keys();
while( keys.hasNext() ) {
String key = (String) keys.next();
System.out.println("Key: " + key);
System.out.println("Value: " + json_array.get(key));
}

as your new to Java and JSON is one of the most famous data interchange language out there, I recommend you to understand the parsing and the structure of JSON thoroughly this example.
for (String key: jsonObject.keySet()){
System.out.println(key);
}
This will fetch you the set of Keys in the JSON.

Related

JSONArray for array of String giving A JSONObject text must begin with '{' at 1 [character 2 line 1]

I am reading a JSON string and trying to get value for a given key.
code to get value from JSON
private static void getKey(JSONObject jsonObject, String key) {
boolean exist = jsonObject.has(key);
Iterator<?> keys;
String nextKey;
if(!exist) {
keys = jsonObject.keys();
while (keys.hasNext()) {
nextKey = (String) keys.next();
System.out.println("Key is :: " + nextKey);
try {
if(jsonObject.get(nextKey) instanceof JSONObject) {
if(!exist) {
getKey(jsonObject.getJSONObject(nextKey), key);
}
} else if(jsonObject.get(nextKey) instanceof JSONArray) {
JSONArray jsonArray = jsonObject.getJSONArray(nextKey);
for(int i = 0; i < jsonArray.length(); i++) {
String arrayValue = jsonArray.get(i).toString();
JSONObject innerJSONObject = new JSONObject(arrayValue.trim());
if(!exist) {
getKey(innerJSONObject, key);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
parseJSONObject(jsonObject, key);
}
}
I am trying to parse this JSON String
String data = "[{\n" +
"\t\"siteName\": \"tvt-ieee\",\n" +
"\t\"personId\": \"43038888\",\n" +
"\t\"editorId\": \"43038888-tvt-ieee\",\n" +
"\t\"emails\": [{\n" +
"\t\t\"emailAddress\": \"02superjh#gmail.com\"\n" +
"\t}],\n" +
"\t\"keywords\": [\"H.1.2 User/Machine Systems\",\"I.2 Artificial Intelligence\"],\n" +
"}]";
JSONArray jsonObject = new JSONArray(data);
getKey(jsonObject.getJSONObject(0), "keywords");
but when I am trying to get value for key "keywords" it is throwing an error like
A JSONObject text must begin with '{' at 1 [character 2 line 1]
please help me how can I solve this issue?
Thank you in advance

How to foreach json or object data with java

I have a return from Web-Service like this :
Object result = envelope.getResponse();
AND the return is like this
[{"nom":"Nexus09","poste":"4319"},{"nom":"Nexus08","poste":"4312"},{"nom":"Nexus07","poste":"4306"}]
I need to foreach the result to get "nom" and "poste" for every {"nom":"Nexus09","poste":"4319"}
THX
Using http://central.maven.org/maven2/org/json/json/20180813/json-20180813.jar Jar,
public static void main(String[] args) {
String input="[{\"nom\":\"Nexus09\",\"poste\":\"4319\"},{\"nom\":\"Nexus08\",\"poste\":\"4312\"},{\"nom\":\"Nexus07\",\"poste\":\"4306\"}]";
JSONArray jsonArray = new JSONArray(input);
jsonArray.forEach(j->System.out.println(j.toString()));
}
To parse the nested JSONObject, It can be done like below,
public static void main(String[] args) {
String input="[{\"nom\":\"Nexus09\",\"poste\":\"4319\"},{\"nom\":\"Nexus08\",\"poste\":\"4312\"},{\"nom\":\"Nexus07\",\"poste\":\"4306\"}]";
JSONArray jsonArray = new JSONArray(input);
for(Object object:jsonArray) {
if(object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject)object;
Set<String> keys =jsonObject.keySet();
for(String key:keys) {
System.out.println(key +" :: "+jsonObject.get(key));;
}
}
}
}
Here is the code to loop through an array of JSON and also get all key-value pairs.
This should work.
Hope it helps.
Code:
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
System.out.println("Key :" + key + " Value :" + json.get(key));
}
for(JSONObject json : result)
{
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
System.out.println("Key :" + key + " Value :" + json.get(key));
}
}

Java - Handling either a string or a list as a string [duplicate]

I'm trying to get the type of the value stored in a JSONObject.
String jString = {"a": 1, "b": "str"};
JSONObject jObj = new JSONObject(jString);
Is it possible to get the type of the value stored at key "a";
something like jObj.typeOf("a") = java.lang.Integer?
You can get the object from the JSON with the help of JSONObject.get() method and then using the instanceof operator to check for the type of Object.
Something on these lines:-
String jString = "{\"a\": 1, \"b\": \"str\"}";
JSONObject jObj = new JSONObject(jString);
Object aObj = jObj.get("a");
if (aObj instanceof Integer) {
// do what you want
}
The best solution is to use JSONObject.get() and check for the type using instanceof operator.
Please note that JSONObject.get() may return an integer as either java.lang.Integer or java.lang.Long, for example, for {a:3,b:100300000000} we see
D/+++ ( 5526): +++a=>class java.lang.Integer:3
D/+++ ( 5526): +++b=>class java.lang.Long:100300000000
I use the code like (note that we use types long and double instead of int and float, and that in my task there may be no nested JSONObject or JSONArray so they are not supported):
for (String k : new AsIterable<String>(json.keys())) {
try {
Object v = json.get(k);
//Log.d("+++","+++"+k+"=>"+v.getClass()+":"+v);
if (v instanceof Integer || v instanceof Long) {
long intToUse = ((Number)v).longValue();
...
} else if (v instanceof Boolean) {
boolean boolToUse = (Boolean)v).booleanValue();
...
} else if (v instanceof Float || v instanceof Double) {
double floatToUse = ((Number)v).doubleValue();
...
} else if (JSONObject.NULL.equals(v)) {
Object nullToUse = null;
...
} else {
String stringToUse = json.getString(k);
...
}
} catch (JSONException e2) {
// TODO Auto-generated catch block
Log.d("exc: "+e2);
e2.printStackTrace();
}
}
where AsIterable lets us use the for(:) loop with an iterator and is defined as:
public class AsIterable<T> implements Iterable<T> {
private Iterator<T> iterator;
public AsIterable(Iterator<T> iterator) {
this.iterator = iterator;
}
public Iterator<T> iterator() {
return iterator;
}
}
I found this way to find data type of element value in JSON / Json. It's working very fine for me.
JSONObject json = new JSONObject(str);
Iterator<String> iterator = json.keys();
if (iterator != null) {
while (iterator.hasNext()) {
String key = iterator.next();
Object value = json.get(key);
String dataType = value.getClass().getSimpleName();
if (dataType.equalsIgnoreCase("Integer")) {
Log.i("Read Json", "Key :" + key + " | type :int | value:" + value);
} else if (dataType.equalsIgnoreCase("Long")) {
Log.i("Read Json", "Key :" + key + " | type :long | value:" + value);
} else if (dataType.equalsIgnoreCase("Float")) {
Log.i("Read Json", "Key :" + key + " | type :float | value:" + value);
} else if (dataType.equalsIgnoreCase("Double")) {
Log.i("Read Json", "Key :" + key + " | type :double | value:" + value);
} else if (dataType.equalsIgnoreCase("Boolean")) {
Log.i("Read Json", "Key :" + key + " | type :bool | value:" + value);
} else if (dataType.equalsIgnoreCase("String")) {
Log.i("Read Json", "Key :" + key + " | type :string | value:" + value);
}
}
}
You can parse all the data as String and then try to convert it to the desired type. At this point you may catch the exception and determine which type is the parsed data.
instanceof is not working for me. In the latest version to get the data type of the field dynamically, instead of using JSONObject.get what you can do is get it as JsonPrimitive like
JsonPrimitive value = json.getAsJsonPrimitive('key');
Now you can call
value.isNumber()
value.isBoolean()
value.isString()

Android: Get the entire array the value/key is in ArrayList<HashMap<String, String>>

I am trying to get v8 from the third array inside following arraylist
String[][] test = {
{"v1","v2","v3","v4","v5","v6","v7"},
{"v1","v2","v3","v4","v5","v6","v7"},
{"v1","v2","v3","v4","v5","v6","v7", "v8"}
};
ArrayList<String[]> test2= new ArrayList<String[]>(Arrays.asList(test));
Log.e("v1: ", "" + test2.get(0));
for (int j = 0; j <= test2.size(); j++) {
for (String[] arrays: test2) {
for (String string2 : arrays) {
if (string2.equalsIgnoreCase("v8")) {
Log.e("LOOOOOOOOOG", "" + test2.indexOf("v8")); // 3
}else {
Log.e("LOOOOOOOOOG", "Cant find it!!");
}
}
}
}
How would i do this?
I currently just get either -1 or Cant find it!!
I am trying to solve the above problem to solve the following HashMap problem.
public static void updateJSONdata() {
mEmailList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_EMAILS_URL);
try {
mEmails = json.getJSONArray("info");
// looping through all emails according to the json object returned
for (int i = 0; i < mEmails.length(); i++) {
JSONObject c = mEmails.getJSONObject(i);
// gets the content of each tag
String email = c.getString(TAG_EMAIL);
String firstName = c.getString(TAG_FNAME);
String lastName = c.getString(TAG_LNAME);
String address = c.getString(TAG_ADDRESS);
String phoneNumber = c.getString(TAG_PHONE);
String city = c.getString(TAG_CITY);
String state = c.getString(TAG_STATE);
String zip = c.getString(TAG_ZIP);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_EMAIL, email);
map.put(TAG_FNAME, firstName);
map.put(TAG_LNAME, lastName);
map.put(TAG_ADDRESS, address);
map.put(TAG_PHONE, phoneNumber);
map.put(TAG_CITY, city);
map.put(TAG_STATE, state);
map.put(TAG_ZIP, zip);
// adding HashList to ArrayList
mEmailList.add(map);
for (HashMap<String, String> maps : mEmailList){
for (Entry<String, String> mapEntry : maps.entrySet()){
String key = mapEntry.getKey();
String value = mapEntry.getValue();
if (value.equals(passedEmail)) {
Log.e("Is this email in the database?", value + " Is in the database!!!");
int index = map.get(key).indexOf(value);
Log.e("mEmailList: ", "" + mEmailList);
// String[] test = mEmailList.indexOf(value);
fullName = mEmailList.get(index).get(TAG_FNAME) +
" " +
mEmailList.get(index).get(TAG_LNAME);
mPhoneNumber = mEmailList.get(index).get(TAG_PHONE);
mAddress = mEmailList.get(index).get(TAG_ADDRESS) + " " +
mEmailList.get(index).get(TAG_CITY) + " " +
mEmailList.get(index).get(TAG_STATE) + " " +
mEmailList.get(index).get(TAG_ZIP);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
It looks like you want the index within the list that contains a map that has a specific email address as one of the values. For that purpose you need to call indexOf on the list, and pass to it a Map.
Something like : mEmailList.indexOf(map).
What you are doing is searching for the index of the first occurrence of a sub-string within another String. That won't give you an index within the list.
In addition, it looks like you are mixing the code that creates the list of maps with the code that searches the list for a specific email.
You are getting -1 because of
test2.indexOf("v8")
The ArrayList test2 contains arrays String[], it doesn't containg "v8". test2, for example, contains { "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8" }, but not "v8".
Note: The methods String#indexOf() and ArrayList#indexOf() are different, so you should read their specification before using them.

How to check the type of a value from a JSONObject?

I'm trying to get the type of the value stored in a JSONObject.
String jString = {"a": 1, "b": "str"};
JSONObject jObj = new JSONObject(jString);
Is it possible to get the type of the value stored at key "a";
something like jObj.typeOf("a") = java.lang.Integer?
You can get the object from the JSON with the help of JSONObject.get() method and then using the instanceof operator to check for the type of Object.
Something on these lines:-
String jString = "{\"a\": 1, \"b\": \"str\"}";
JSONObject jObj = new JSONObject(jString);
Object aObj = jObj.get("a");
if (aObj instanceof Integer) {
// do what you want
}
The best solution is to use JSONObject.get() and check for the type using instanceof operator.
Please note that JSONObject.get() may return an integer as either java.lang.Integer or java.lang.Long, for example, for {a:3,b:100300000000} we see
D/+++ ( 5526): +++a=>class java.lang.Integer:3
D/+++ ( 5526): +++b=>class java.lang.Long:100300000000
I use the code like (note that we use types long and double instead of int and float, and that in my task there may be no nested JSONObject or JSONArray so they are not supported):
for (String k : new AsIterable<String>(json.keys())) {
try {
Object v = json.get(k);
//Log.d("+++","+++"+k+"=>"+v.getClass()+":"+v);
if (v instanceof Integer || v instanceof Long) {
long intToUse = ((Number)v).longValue();
...
} else if (v instanceof Boolean) {
boolean boolToUse = (Boolean)v).booleanValue();
...
} else if (v instanceof Float || v instanceof Double) {
double floatToUse = ((Number)v).doubleValue();
...
} else if (JSONObject.NULL.equals(v)) {
Object nullToUse = null;
...
} else {
String stringToUse = json.getString(k);
...
}
} catch (JSONException e2) {
// TODO Auto-generated catch block
Log.d("exc: "+e2);
e2.printStackTrace();
}
}
where AsIterable lets us use the for(:) loop with an iterator and is defined as:
public class AsIterable<T> implements Iterable<T> {
private Iterator<T> iterator;
public AsIterable(Iterator<T> iterator) {
this.iterator = iterator;
}
public Iterator<T> iterator() {
return iterator;
}
}
I found this way to find data type of element value in JSON / Json. It's working very fine for me.
JSONObject json = new JSONObject(str);
Iterator<String> iterator = json.keys();
if (iterator != null) {
while (iterator.hasNext()) {
String key = iterator.next();
Object value = json.get(key);
String dataType = value.getClass().getSimpleName();
if (dataType.equalsIgnoreCase("Integer")) {
Log.i("Read Json", "Key :" + key + " | type :int | value:" + value);
} else if (dataType.equalsIgnoreCase("Long")) {
Log.i("Read Json", "Key :" + key + " | type :long | value:" + value);
} else if (dataType.equalsIgnoreCase("Float")) {
Log.i("Read Json", "Key :" + key + " | type :float | value:" + value);
} else if (dataType.equalsIgnoreCase("Double")) {
Log.i("Read Json", "Key :" + key + " | type :double | value:" + value);
} else if (dataType.equalsIgnoreCase("Boolean")) {
Log.i("Read Json", "Key :" + key + " | type :bool | value:" + value);
} else if (dataType.equalsIgnoreCase("String")) {
Log.i("Read Json", "Key :" + key + " | type :string | value:" + value);
}
}
}
You can parse all the data as String and then try to convert it to the desired type. At this point you may catch the exception and determine which type is the parsed data.
instanceof is not working for me. In the latest version to get the data type of the field dynamically, instead of using JSONObject.get what you can do is get it as JsonPrimitive like
JsonPrimitive value = json.getAsJsonPrimitive('key');
Now you can call
value.isNumber()
value.isBoolean()
value.isString()

Categories

Resources