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));
}
}
Related
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
I have the JSON below:
"total":"2",
"offset":"1",
"limit":"2",
"results":[{
"code":1,
"title":"RESTAURANTE SADOCHE",
"contact":{
"code":10,
"name":"HENRIQUE BARBALHO",
"company":{
"code":100,
"name":"RESTAURANTE SADOCHE LTDA-ME"
}
}
},
{
"code":2,
"title":"ARNALDO GRILL",
"contact":{
"code":20,
"name":"FĂTIMA COSTA",
"company":{
"code":200,
"name":"COSTA NATAL RESTAURANTE EIRELI"
}
}
}]
I turned this JSON into a Java HashMap using the Gson library.
Map<String, Object> retMap = new Gson().fromJson(jsonUpString, new TypeToken<HashMap<String, Object>>(){}.getType());
I need to dynamically read some properties of this created hashmap. Ex: title, name of contact and name of company.
Sometimes these properties (title, name of contact and name of company) can be inside lists.
Below my code:
String propertyName = "name";
String nesting = "results;contact;company";
String[] levels = nesting.split(";");
Map map = new HashMap();
map = retMap;
for (int i = 0; i < niveis.length; i++) {
map = (Map)map.get(levels[i]);
System.out.println(map);
if (i == levels.length - 1) {
System.out.println(map.get(propertyName));
}
}
But if the properties (results, contact or company) return more than one object, the JSON returns them as lists, and I can't get the information I need.
I solved the problem using...
private static void leJSON(Object object) {
if (object instanceof JSONObject) {
Set < String > ks = ((JSONObject) object).keySet();
for (String key: ks) {
Object value = ((JSONObject) object).get(key);
if (value != null) {
System.out.printf("%s=%s (%s)\n", key, value, value.getClass().getSimpleName());
if (value.getClass().getSimpleName().equalsIgnoreCase("JSONArray")) {
JSONArray ja = (JSONArray) value;
for (int i = 0; i < ja.size(); i++) {
leJSON(ja.get(i));
}
}
if (value.getClass().getSimpleName().equalsIgnoreCase("JSONObject")) {
leJSON(value);
}
}
}
}
}
main method...
String json = "{...}";
JSONObject object = (JSONObject) JSONValue.parse(jsonString2);
readJSON(object);
Need to know how to merge these two object
{"a":"1",
"b":"2"
}
{"c":"4",
"d":[{}]
}
To give
{a,b,c,d} with their values
public static void main(String...strings) throws JSONException {
String s1 = "{\"a\":\"1\",\"b\":\"2\"}";
String s2 = "{\"c\":\"4\",\"d\":[{}]}";
JSONObject jsonObject1 = new JSONObject(s1);
JSONObject jsonObject2 = new JSONObject(s2);
Iterator itr = jsonObject2.keys();
while(itr.hasNext()) {
String key = (String) itr.next();
jsonObject1.put(key, jsonObject2.get(key));
}
System.out.println(jsonObject1.toString());
}
Output : {"a":"1","b":"2","c":"4","d":[{}]}
Another way assuming you have simple JSON data as u have shown in the example
public static void main(String...strings) throws JSONException {
String s1 = "{\"a\":\"1\",\"b\":\"2\"}";
String s2 = "{\"c\":\"4\",\"d\":[{}]}";
int firstIndex = s2.indexOf("{");
int lastIndex = s1.lastIndexOf("}");
String result = s1.substring(0, lastIndex)+"," + s2.substring(firstIndex+1);
System.out.println(result);
JSONObject jsonObject = new JSONObject(result);
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println("Key :: "+key+" value :: "+jsonObject.get(key));
}
}
output :: {"a":"1","b":"2","c":"4","d":[{}]} Key :: a value :: 1 Key
:: b value :: 2 Key :: c value :: 4 Key :: d value :: [{}]
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.
Lets say I gave a JSONObject
{
"person":{"name":"Sam", "surname":"ngonma"},
"car":{"make":"toyota", "model":"yaris"}
}
How do I update some of the values in the JSONObject?
Like below :
String name = jsonArray.getJSONObject(0).getJSONObject("person").getString("name");
name = "Sammie";
Use the put method: https://developer.android.com/reference/org/json/JSONObject.html
JSONObject person = jsonArray.getJSONObject(0).getJSONObject("person");
person.put("name", "Sammie");
Remove key and then add again the modified key, value pair as shown below :
JSONObject js = new JSONObject();
js.put("name", "rai");
js.remove("name");
js.put("name", "abc");
I haven't used your example; but conceptually its same.
Hello I can suggest you universal method. use recursion.
public static JSONObject function(JSONObject obj, String keyMain,String valueMain, String newValue) throws Exception {
// We need to know keys of Jsonobject
JSONObject json = new JSONObject()
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if object is just string we change value in key
if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null)) {
if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain))) {
// put new value
obj.put(key, newValue);
return obj;
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
function(obj.getJSONObject(key), keyMain, valueMain, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i=0;i<jArray.length();i++) {
function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
}
}
}
return obj;
}
It should work. If you have questions, go ahead.. I'm ready.
Generic way to update the any JSONObjet with new values.
private static void updateJsonValues(JsonObject jsonObj) {
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
JsonElement element = entry.getValue();
if (element.isJsonArray()) {
parseJsonArray(element.getAsJsonArray());
} else if (element.isJsonObject()) {
updateJsonValues(element.getAsJsonObject());
} else if (element.isJsonPrimitive()) {
jsonObj.addProperty(entry.getKey(), "<provide new value>");
}
}
}
private static void parseJsonArray(JsonArray asJsonArray) {
for (int index = 0; index < asJsonArray.size(); index++) {
JsonElement element = asJsonArray.get(index);
if (element.isJsonArray()) {
parseJsonArray(element.getAsJsonArray());
} else if (element.isJsonObject()) {
updateJsonValues(element.getAsJsonObject());
}
}
}
public static JSONObject updateJson(JSONObject obj, String keyString, String newValue) throws Exception {
JSONObject json = new JSONObject();
// get the keys of json object
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if the key is a string, then update the value
if ((obj.optJSONArray(key) == null) && (obj.optJSONObject(key) == null)) {
if ((key.equals(keyString))) {
// put new value
obj.put(key, newValue);
return obj;
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
updateJson(obj.getJSONObject(key), keyString, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i = 0; i < jArray.length(); i++) {
updateJson(jArray.getJSONObject(i), keyString, newValue);
}
}
}
return obj;
}
Recursive way to update value in depth in Kotlin
Example: setJsonValue("obj1/obj2/keyToUpdate", "new value")
fun setJsonValue(path: String, value: Any?) {
setJsonValueRec(
path = path.split("/"),
index = 0,
obj = jsonObj,
value = value
)
}
private fun setJsonValueRec(path: List<String>, index: Int, obj: JSONObject, value: Any?): JSONObject {
return obj.put(
path[index],
when (index) {
path.lastIndex -> value
else -> setJsonValueRec(
path = path,
index = index + 1,
obj = obj.getJSONObject(path[index]),
value = value
)
}
)
}