Json Object - Getting the Key and the Value - java

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");

Related

How to Traverse Complex JSON and put into a Map?

I tried few days to get this done. but could`t .
What i want is Traverse any given JSON and put Key and Value pair into a map. As a sample consider this JSON
String test = {
"RechargeRequest":{
"RechargeSerialNo":"2645",
"RechargeChannelID":"3",
"RechargeObj":{
"SubAccessCode":{
"PrimaryIdentity":"763500001"
}
},
"RechargeInfo":{
"CashPayment":[
{
"Amount":"30"
}
]
}
}
}
What i have tried so far
JSONObject jsonObj = new JSONObject(test);
Iterator<String> keys = jsonObj.keys();
Map<String,String> map = new HashMap<>();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObj.get(key) instanceof JSONObject) {
}else if(jsonObj.get(key) instanceof JSONArray){
}else{
}
}
Maps value should be like ( "RechargeChannelID","3")
( "Amount":"30")
Can anybody help me please?
Thanks,
If I understood correctly you want to flatten your json file into one level then map it to key and value pairs, kindly check the link below:
How to deserialize JSON into flat, Map-like structure?

How to iterate over JSONObject and found id by value which already known, for example I want to get id of value "ТС-41" how can I do it?

{
"0":"",
"54049":"ОП.мз-61а",
"100606":"КМ-41",
"100609":"МТ-41",
"100612":"ЕМ-41",
"100684":"ХК-51",
"100685":"ЕМ-51",
"100687":"КМ-51",
"100688":"МТ-51",
"100718":"ХК-51/1",
"100719":"ХК-51/2",
"100748":"ТС-61",
"100749":"ТС-61/1",
"100750":"ТС-61/2",
"100754":"ЕМ-61",
"100758":"ІМ-61/1МБ",
"100759":"ІМ-61/2ГТ",
"100760":"МБ-61",
"100767":"ТС-51",
"100770":"ТС-41",
"100777":"ТС.м-61",
"100778":"МТ.м-61",
"100779":"ЕМ.м-61",
"100780":"ТМ.м-61",
"100781":"ТМ.м-62",
"100782":"ГМ.м-61",
"100783":"ВІ.м-61",
"100786":"ХМ.м-61"
}
You'll need to iterate over the JSONObject keys and compare the value until a match.
final String knownValue = "TC-41";
final Iterator<String> iterable = jsonObject.keys();
while (iterable.hasNext()) {
String key = iterable.next();
if (jsonObject.getString(key).equals(knownValue)) {
// key has the value you are looking for
return;
}
}
Use JSON Classes for parsing
JSONObject mainObject = new JSONObject(Your_Sring_data);
String id = mainObject .getString("100770");
//here in this **id** string you can get value for **"TC-41"**

Get JSON keys with values

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);
}

How can I parse JSONObject without knowing the name?

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.....
}
}

Convert a String to HashMap

I am getting this string from a service. I want a map or json out of this. It should look like this.
Map output
Total time taken:226006
nodea:10615
nodez:5308'
String timingTrace = "Total time taken:226006.,"
+ "time spent in nodes:{\"nodea\":{\"timeTaken\":10615},\"nodez\":{\"timeTaken\":5308}}\"";
What I have tried so for is the below code. Can I do something better? Any library that can easily convert the above string to map.
if (timingTrace != null) {
arrayofTimeStamp = StringUtils.splitByWholeSeparator(StringUtils.remove(timingTrace, " "), ".,");
}
String[] totaltime = StringUtils.split(arrayofTimeStamp[0], ":")
Map<String,Object> timestamps = new HashMap<String, Object>();
timestamp.put(totaltime[0], totaltime[1]);
String[] nodetimestamp = StringUtils.splitByWholeSeparator(arrayofTimeStamp[1], "time spent in nodes:");
getMapped(nodetimestamp[1]);
public void getMapped(String json) throws JSONException, ParseException {
JSONObject obj = new JSONObject(json);
Iterator<String> keys = obj.keys();
while (keys.hasNext()) {
String key = keys.next();
String timetaken = JsonPath.read(json, "$." + key + ".timeTaken");
timestamp.put(key, timetaken);
}
}
You are using timestamp Map<> object in function getMapped(String json) that give you error because you haven't passed it you declare in function.
To get output you have mention change write below code instead of function getMapped(String json) :
JSONObject obj = new JSONObject(nodetimestamp[1]);
Iterator<String> keys = obj.keys();
while (keys.hasNext())
{
String key = keys.next();
String timetakenStr = obj.getString(key);
JSONObject child = new JSONObject(timetakenStr);
timestamps.put(key, child.getString("timeTaken"));
}
Using above code your Map<> will contain same what you mention.
OutPut :
{nodea=10615, Total time taken=226006, nodez=5308}

Categories

Resources