I have json string like this:
{
"2":{
"id":"2",
"first":"3",
"last":"2",
"ilike":"1",
"created_at":"2015-06-30 16:57:39",
"liketo":"2",
"firstname":"FirstName",
"lastname":"LastName",
"birthday":null
}
}
How can I parse JSONObject without knowing the name "2"
just moving to the next array?
String json="" // place your json format here in double Quotes with proper escapes .......
jObject = new JSONObject(json.trim());
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( jObject.get(key) instanceof JSONObject ) {
// do what ever you want with the JSONObject.....
}
}
Related
I am given a JSON that will come in this format:
"template":{
"mod1":[
{
"param1":"55",
"param2":"5",
"param3":"somedata"
}
],
"mod2":[
{
"param1":"somedata",
"param2":"somedata"
}
],
"mod3":[
{
"param1":"somedata",
"param2":"somedata",
"param3":"somedata"
}
],
"mod4":[
{
"param1":"somedata",
"param2":"somedata"
}
],
"mod5":[
{
"param1":"somedata"
}
]
}
}
What is the easiest way to parse it? What I'd like is to get the params inside the mod and their associated values together, to store into a database. The way I am doing it is as so:
JSONObject obj = new JSONObject(json);
System.out.println(obj);
Iterator<String> keys = obj.keys();
while(keys.hasNext()) {
String key = keys.next();
JSONObject currTemplate = (JSONObject) obj.get(key);
if(currTemplate instanceof JSONObject) {
System.out.println("LIST OF ALL MODULES : " + currTemplate);
Iterator<String> currObjKeys = ((JSONObject) currTemplate).keys();
while(currObjKeys.hasNext()) {
String currObjKey = currObjKeys.next();
System.out.println("MODULE: " + currObjKey);
JSONArray array = currTemplate.getJSONArray(currObjKey);
System.out.println("ARRAY: " + array);
for(int i = 0; i < array.length(); i++){
JSONObject object = array.getJSONObject(i);
String[] names = JSONObject.getNames(object);
for(String name: names) {
System.out.println("PARAMS");
System.out.println(name);
System.out.println(object.get(name));
}
}
}
}
And it currently prints what I need correctly. What I am asking is if there is a more efficient way to do it - the way I currently have it is O(N^4), and I was wondering if anyone had any idea to parse the JSON in a more efficient way. Note: the params will not always be in form param1, param2, the names will always be different. Just changed it for confidentiality sake.
Thank you in advance.
JSONArray arr =
[
{"key1":"value1"},
{"key2":"value2"},
{"key3":"value3"},
{"key4":"value4"}
]
arr.get("key1") throws error. How can I get the value by key in JSONArray?
arr.getString("key1") also throws error. Should I loop through the array? Is it the only way to do it?
What is the error?
In Eclipse Debug perspective, these expressions returns as; error(s)_during_the_evaluation
You can parse your jsonResponse like below code :
private void parseJsonData(String jsonResponse){
try
{
JSONArray jsonArray = new JSONArray(jsonResponse);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String value1 = jsonObject1.optString("key1");
String value2 = jsonObject1.optString("key2");
String value3 = jsonObject1.optString("key3");
String value4 = jsonObject1.optString("key4");
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
Sounds like you want to find a specific key from an array of JSONObjects. Problem is, it's an array, so you have to iterate over each element. One solution, assuming no repeat keys is...
private Object getKey(JSONArray array, String key)
{
Object value = null;
for (int i = 0; i < array.length(); i++)
{
JSONObject item = array.getJSONObject(i);
if (item.keySet().contains(key))
{
value = item.get(key);
break;
}
}
return value;
}
Now, let's say you want to find the value of "key1" in the array. You can get the value using the line: String value = (String) getKey(array, "key1"). We cast to a string because we know "key1" refers to a string object.
for (int i = 0; i < arr.length(); ++i) {
JSONObject jsn = arr.getJSONObject(i);
String keyVal = jsn.getString("key1");
}
You need to iterate through the array to get each JSONObject. Once you have the object of json you can get values by using keys
You can easy get a JSON array element by key like this:
var value = ArrName['key_1']; //<- ArrName is the name of your array
console.log(value);
Alternatively you can do this too:
var value = ArrName.key_1;
That's it!
I have been trying to get the key and value of my JSONObject. I have no idea why this isn't working, because String key is clearly a string?
My code:
JSONObject obj = new JSONObject(historie2.getData());
Iterator<?> keys = obj.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
String value = obj.getString(key); //This is where the error comes
}
The JSONObject:
{
"relatie_website": ["www.apple.com"],
"relatie_kvknummer": ["NL3234234"],
"relatie_naam": ["Apple international inc."],
"relatie_d400code": [null],
"relatie_zoeknaam": ["APPLE INC"],
"relatie_debiteurnummer": ["3523523"],
"relatie_btwnummer": ["332342"]
}
This is the error I have been getting:
org.json.JSONException: JSONObject["relatie_website"] not a string.
You should change your object to be sth like that :
{
"relatie_website": "www.apple.com",
"relatie_kvknummer": "NL3234234",
"relatie_naam": "Apple international inc.",
"relatie_d400code": null,
"relatie_zoeknaam": "APPLE INC",
"relatie_debiteurnummer": "3523523",
"relatie_btwnummer": "332342"
}
Because the problem is that your values are an array and not a string.
But if you need te keep your values in an array you can change your code to support the arrays :
JSONObject obj = new JSONObject(historie2.getData());
Iterator<?> keys = obj.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
JSONArray value = obj.getJSONArray(key);
}
And you will have a JsonArray that you can manipulate as you want by doing sth like that :
for (int i = 0; i < value.length(); i++) {
String val = value.getString(i).toString();
logger.info("val : " + val);
}
Let I have a string, json string.
{"cond":{"to_email":"b#b.c"},"ret":"all"}
Now I want to parse it using json simple parser in java.
I am giving the code...
try{
//String s=request.getParameter("data");
String s="{\"cond\":{\"to_email\":\"b#b.c\"},\"ret\":\"all\"}";
JSONParser jsp=new JSONParser();
if(s == null || s.equals("")){
//problem
String json="{\"error\":\"error\",\"message\":\"no json data\"}";
response.getWriter().println(json);
}else{
JSONObject obj=(JSONObject) jsp.parse(s); //only object is allowed
JSONObject condObj=(JSONObject) jsp.parse(""+obj.get("cond"));
JSONObject returnObj=(JSONObject) jsp.parse(""+obj.get("ret"));
System.out.println(condObj);
}
Now the problem is that it's giving error...
Unexpected character (a) at position 0.
But if I remove the "ret" : "all" then it's working well.
Here in the example I printed condObj only but if I print retObj then it's giving null. So, the problem is the the "ret" : "all" part...
But it's a correct json. I checked it. How to get out of this problem??
The thing is very simple!
The key "cond" represents an complex JSONObject but the key "ret" just a String. So the parsing fails in this case. I dont know which JSON-libary you are using, but have a look for an JSONObject#getString(String key) method to get the value.
Good luck
UPDATE (with the JSON lib I use)
try{
//String s=request.getParameter("data");
String s="{\"cond\":{\"to_email\":\"b#b.c\"},\"ret\":\"all\"}";
if(s == null || s.equals("")){
//problem
String json="{\"error\":\"error\",\"message\":\"no json data\"}";
}else{
JSONObject obj= new JSONObject(s);
JSONObject condObj=(JSONObject) obj.getJSONObject("cond");
String returnObj= obj.getString("ret");
System.out.println(condObj);
System.out.println(returnObj);
}
}
catch (Exception e) {
e.printStackTrace();
}
Just following the above answer ,here is a simple parser.
import java.util.Set;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class ParseJson {
public static void main(String[] args) throws Exception {
String s = "{\"cond\":{\"to_email\":\"b#b.c\"},\"ret\":\"all\"}";
JSONParser jsp = new JSONParser();
if (s == null || s.equals("")) {
String json = "{\"error\":\"error\",\"message\":\"no json data\"}";
} else {
JSONObject obj = (JSONObject) jsp.parse(s);
JSONObject condObj = (JSONObject) jsp.parse("" + obj.get("cond"));
Set<String> keys = obj.keySet();
for (String key : keys) {
System.out.println("Key : " + key);
System.out.print("Value : " +obj.get(key));
System.out.println();
}
}
}
}
This prints both the key and value pairs for you. We can add conditionals for specific keys.
Key : ret
Value : all
Key : cond
Value : {"to_email":"b#b.c"}
I am a newbie to JSON . So If this is a very basic doubt don't scold me . I have a JSON Object Reference and I want to get the Key(Object has only one Key Value Pair) . How do I get it in Java ?
You can use jsonObject.keys() for getting all keys. Then you may iterate over keys to get the first key out of them like :
Iterator<String> keys = jsonObject.keys();
if( keys.hasNext() ){
String key = (String)keys.next(); // First key in your json object
}
json.keys() will give all the keys in your JSONObject where json is an object of JSONObject
Recursively search for a key, and if found, return its value
String recurseKeys(JSONObject jObj, String findKey) throws JSONException {
Iterator<?> keys = jObj.keys();
String key = "";
while (keys.hasNext() && !key.equalsIgnoreCase(findKey)) {
key = (String) keys.next();
if (key.equalsIgnoreCase(findKey)) {
return jObj.getString(key);
}
if (jObj.get(key) instanceof JSONObject) {
return recurseKeys((JSONObject)jObj.get(key), findKey);
}
}
return "";
}
Usage:
JSONObject jObj = new JSONObject(jsonString);
String extract = recurseKeys(jObj, "extract");