I have a json file like this:
{
"list": [
{
"ID" : "1",
"value" : "value is one"
}
{
"ID" : "2",
"value" : "value is two"
}
{
"ID" : "3",
"value" : "value is three"
}
{
"ID" : "4",
"value" : "value is four"
}
]
}
what I want to do is read the josn file and returns the message based on the ID i specify. So for example
if (this.list.containsKey("1"))
{
return this.list.get(messageTitle);
}
That's what I tried but it returns all the values and ID.
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("jsonFile.json"));
JSONObject jsonObject = (JSONObject) obj;
// loop array
JSONArray msg = (JSONArray) jsonObject.get("list");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
How try like this,
JSONArray msg = (JSONArray) jsonObject.get("list");
for(int i = 0;i < msg.length();i++ ) {
JSONObject jsonObj = msg.getJSONObject(i);
//now get id & value
int id = jsonObj.getInt("ID");
String value = jsonObj.getString("value");
if (1 == id) {
//now 'value' is what you want
System.out.println(value);
}
}
Note: can break the loop when the result is satisfied.
You can try with TypeReference using ObjectMapper to convert it into appropriate Map object.
sample code:
BufferedReader reader = new BufferedReader(new FileReader(new File("jsonFile.json")));
TypeReference<Map<String, ArrayList<Map<String, String>>>> typeRef = new TypeReference<Map<String, ArrayList<Map<String, String>>>>() {};
ObjectMapper mapper = new ObjectMapper();
try {
Map<String, ArrayList<Map<String, String>>> data = mapper.readValue(reader, typeRef);
ArrayList<Map<String, String>> list = data.get("list");
for (Map<String, String> map : list) {
if (map.get("ID").equals("1")) {
System.out.println(map.get("value"));
}
}
} catch (Exception e) {
System.out.println("There might be some issue with the JSON string");
}
output:
value is one
Related
I have a JsonElement:
JsonElement testCaseParametersJson = batchItem.getTestCase().getToolParameters().get("testCaseParameters");
of which assigns the following:
["dessert", "place", "tvShow"]
And I have a JsonArray:
JsonObject testParametersJson = batchItem.getTestParameters().getAsJsonObject();
of which assigns the following:
{"dessert": "cookies", "tvShow": "survivor", "color" : "blue"}
I'd appreciate some advice on how to check if the key in the JsonArray exists as an item in the JsonElement.
Using Gson library, you can get the String values from your JSONElement / JSONObject and do the following:
String jsonObject = "{\"dessert\": \"cookies\", \"tvShow\": \"survivor\", \"color\" : \"blue\"}";
String jsonArray = "[\"dessert\", \"place\", \"tvShow\"]";
Map<String, String> objMap = new Gson().fromJson(jsonObject, new TypeToken<HashMap<String, String>>() {}.getType());
List<String> arrayVals = new Gson().fromJson(jsonArray, new TypeToken<List<String>>(){}.getType());
for(Entry<String, String> entry : objMap.entrySet()) {
for (String val : arrayVals) {
if (entry.getKey().equals(val)) {
System.out.println("Found value in key set: " + val);
}
}
}
Code can be summarized, and if using Java 8, you can try "forEach" loop according to your needs.
I have a sample JSON as below. I need to get the individual fields like ASIdentifer and ExternalIdentifer. I have stored this JSON data in a string.
Using GoogleJson as the module(ggson)
JSON data:
{
"DeviceCommon": {
"ASIdentifier": "123",
"DatadeliveyMechanism": "notify",
"MobileOriginatorCallbackReference": {
"url": "http://application.example.com/inbound/notifications/modatanotification/"
},
"AccessiblityCallbackReference": {
"url": "http://application.example.com/inbound/notifications/accessibilitystatusnotification"
}
},
"DeviceList": [{
"ExternalIdentifer": "123456#mydomain.com",
"msisdn": "123456",
"senderName": "Device1",
"MobileOriginatorCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/modatanotification/"
},
"ConfigurationResultCallbackReference": {
"notifyURL": "http://application.example.com/inbound/notifications/configurationResult"
},
"ASreferenceID": "AS000001",
"NIDDduration": "1d"
}]
}
I created the POJO classes and parsed the data using below code
data = new Gson().fromJson(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"), Data.class);
System.out.println(data);
Output:
Data{
deviceCommon=DeviceCommon{
asIdentifier='123'
datadeliveyMechanism='notify'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
accessiblityCallbackReference=http://application.example.com/inbound/notifications/accessibilitystatusnotification
}
deviceList=[DeviceListEntry{
externalIdentifer='123456#mydomain.com'
msisdn='123456'
senderName='Device1'
mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
configurationResultCallbackReference=http://application.example.com/inbound/notifications/configurationResult
asReferenceID='AS000001'
nidDduration='1d'
}]
}
String jsonInString = gson.toJson(data);
System.out.println("String is"+ jsonInString);
Output:
String is{"DeviceCommon":{"ASIdentifier":"123","DatadeliveyMechanism":"notify","MobileOriginatorCallbackReference":{"url":"http://application.example.com/inbound/notifications/modatanotification/"},"AccessiblityCallbackReference":{"url":"http://application.example.com/inbound/notifications/accessibilitystatusnotification"}},"DeviceList":[{"ExternalIdentifer":"123456#mydomain.com","msisdn":"123456","senderName":"Device1","MobileOriginatorCallbackReference":{"notifyURL":"http://application.example.com/inbound/notifications/modatanotification/"},"ConfigurationResultCallbackReference":{"notifyURL":"http://application.example.com/inbound/notifications/configurationResult"},"ASreferenceID":"AS000001","NIDDduration":"1d"}]}
I need to parse this JSON string to get individual fields like ExternalIdentifier and ASIdentifier.
I tried something like this but it is not working.
JsonObject jobj = new Gson().fromJson(jsonInString, JsonObject.class);
String result = jobj.get("ASIdentifier").toString();
System.out.println("value is"+ result);
Note: ExternalIdentifier is within the array, so I need to loop through the array to find it.
Can you please tell me what I'm doing wrong?
Possible solution:
String result = jobj.get("DeviceCommon").getAsJsonObject().get("ASIdentifier").getAsString();
System.out.println("ASIdentifier: "+ result);
JsonArray jsonArray = jobj.get("DeviceList").getAsJsonArray();
for (JsonElement device : jsonArray ) {
result = device.getAsJsonObject().get("ExternalIdentifer").getAsString();
System.out.println("ExternalIdentifer: "+ result);
}
Output:
ASIdentifier: 123
ExternalIdentifer: 123456#mydomain.com
public static void printJson(JsonElement jsonElement,String key) {
// Check whether jsonElement is JsonObject or not
if (jsonElement.isJsonObject()) {
Set<Entry<String, JsonElement>> ens = ((JsonObject) jsonElement).entrySet();
if (ens != null) {
// Iterate JSON Elements with Key values
for (Entry<String, JsonElement> en : ens) {
// System.out.println("##key is"+en.getKey() + " : ");
printJson(en.getValue(), en.getKey());
// System.out.println(en.getValue().getAsString());
// System.out.println(jsonElement.getAsString());
}
}
}
// Check whether jsonElement is Primitive or not
else if (jsonElement.isJsonPrimitive()) {
// print value as String
System.out.println("###key is"+key);
System.out.println("### value is"+jsonElement.getAsString());
}
else if (jsonElement.isJsonArray()) {
JsonArray jarr = jsonElement.getAsJsonArray();
// Iterate JSON Array to JSON Elements
System.out.println("\n###Array size is"+ jarr.size());
for (JsonElement je : jarr) {
printJson(je,key);
}
}
}
I'm trying to parse Json string using java, I have stuck up with some scenario.
See below is my JSON String:
"NetworkSettings": {
"Ports": {
"8080/tcp": [ // It will change dynamically like ("8125/udp" and "8080/udp" etc....)
{
"HostIp": "0.0.0.0",
"HostPort": "8080"
}
]
}
}
I try to parse the above json string by using the following code:
JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
if(NetworkSettings_obj.has("Ports"))
{
JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
if(ntw_Ports_obj.has("8080/tcp"))
{
JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");
JsonObject ntwtcp_obj=arr_ntwtcp.get(0).getAsJsonObject();
if(ntwtcp_obj.has("HostIp"))
{
ntw_HostIp=ntwtcp_obj.get("HostIp").toString();
System.out.println("Network HostIp = "+ntw_HostIp);
}
if(ntwtcp_obj.has("HostPort"))
{
ntw_HostPort=ntwtcp_obj.get("HostPort").toString();
System.out.println("Network HostPort = "+ntw_HostPort);
}
}
else
{
ntw_HostIp="NA";
ntw_HostPort="NA";
}
}
else
{
ntw_HostIp="NA";
ntw_HostPort="NA";
}
In my code I have used this code
JsonArray arr_ntwtcp=(JsonArray)ntw_Ports_obj.get("8080/tcp");
to get the value of "8080/tcp"
How can I get the values of dynamically changing key like ("8125/udp","8134/udp", etc...)
Note: I'm using gson library for parsing
After modification
public static void main(String args[])
{
try
{
JsonParser parser = new JsonParser();
JsonObject obj=(JsonObject)parser.parse(new FileReader("sampleJson.txt"));
System.out.println("obj = "+obj);
JsonObject NetworkSettings_obj=(JsonObject)obj.get("NetworkSettings");
if(NetworkSettings_obj.has("Ports"))
{
JsonObject ntw_Ports_obj=(JsonObject)NetworkSettings_obj.get("Ports");
System.out.println("ntw_Ports_obj = "+ntw_Ports_obj);
Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
List keys = new ArrayList();
System.out.println(keyObjects instanceof Map); //**** here the statement prints false
if (keyObjects instanceof Map) // *** so controls doesn't enters into the if() condition block *** //
{
Map map = (Map) keyObjects;
System.out.println("Map = "+map);
keys.addAll(map.keySet());
String key = (String) keys.get(0);
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println("Array List = "+jArray);
}
}
}
catch(Exception e)
{
}
}
You can do something like that (not tested but should be ok) :
if (ntw_Ports_obj.isJsonArray()) {
Iterator it = ntw_Ports_obj.getAsJsonArray().iterator();
while (it.hasNext()) {
JsonElement element = (JsonElement) it.next();
if(element.isJsonArray()){
JsonArray currentArray = element.getAsJsonArray();
// Do something with the new JsonArray...
}
}
}
So your problem is the key 8080/tcp is not fixed and it may change. when this situation you can try like this to get the value of the Dynamic key.
Set<Map.Entry<String, JsonElement>> entrySet = ntw_Ports_obj
.entrySet();
for (Map.Entry<String, JsonElement> entry : entrySet) {
String key = entry.getKey();
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println(jArray);
}
Edit:
Object keyObjects = new Gson().fromJson(ntw_Ports_obj, Object.class);
List keys = new ArrayList();
/** for the given json there is a one json object within the 'Ports' so the 'keyObjects' will be the 'Map'**/
if (keyObjects instanceof Map) {
Map map = (Map) keyObjects;
keys.addAll(map.keySet());
/**
* keys is a List it may contain more than 1 value, but for the given
* json it will contain only one value
**/
String key = (String) keys.get(0);
JsonArray jArray = (JsonArray) ntw_Ports_obj.get(key);
System.out.println(jArray);
}
I am trying to iterate over a json object using json simple. I have seen answers where you can do a getJSONObject("child") from
{ "child": { "something": "value", "something2": "value" } }
But what if I just have something
{
"k1":"v1",
"k2":"v2",
"k3":"v3"
}
And want to iterate over that json object. This:
Iterator iter = jObj.keys();
Throws:
cannot find symbol
symbol : method keys()
location: class org.json.simple.JSONObject
Assuming your JSON object is saved in a file "simple.json", you can iterate over the attribute-value pairs as follows:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("simple.json"));
JSONObject jsonObject = (JSONObject) obj;
for(Iterator iterator = jsonObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
System.out.println(jsonObject.get(key));
}
You can do like this
String jsonstring = "{ \"child\": { \"something\": \"value\", \"something2\": \"value\" } }";
JSONObject resobj = new JSONObject(jsonstring);
Iterator<?> keys = resobj.keys().iterator();
while(keys.hasNext() ) {
String key = (String)keys.next();
if ( resobj.get(key) instanceof JSONObject ) {
JSONObject xx = new JSONObject(resobj.get(key).toString());
Log.d("res1",xx.getString("something"));
Log.d("res2",xx.getString("something2"));
}
}
In Java 8 we can use lambdas
void handleJSONObject(JSONObject jsonObject) {
jsonObject.keys().forEachRemaining(key -> {
Object value = jsonObject.get(key);
logger.info("Key: {0}\tValue: {1}", key, value);
}
}
Below is the code to iterate through org.google.jso.JsonElemet set and filter out the specific JsonElement by key:
Predicate<Map.Entry<String, JsonElement>> keyPredicate = a -> a.getKey().equalsIgnoreCase(jsonAttributeKey);
Predicate<Map.Entry<String, JsonElement>> valuePredicate = a -> a.getValue()!= null && !a.getValue().isJsonNull();
return responseJson.getAsJsonObject().entrySet().stream()
.filter(keyPredicate.and((valuePredicate)))
.findAny()
.orElseThrow(() -> {
System.out.println(jsonAttributeKey +" tag not exist in the json");
return NGPExceptionFactory.getNGPException(errorCode);
})
.getValue();
What is the best way to combine (merge) two JSONObjects?
JSONObject o1 = {
"one": "1",
"two": "2",
"three": "3"
}
JSONObject o2 = {
"four": "4",
"five": "5",
"six": "6"
}
And result of combining o1 and o2 must be
JSONObject result = {
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6"
}
I have your same problem: I can't find the putAll method (and it isn't listed in the official reference page).
So, I don't know if this is the best solution, but surely it works quite well:
//I assume that your two JSONObjects are o1 and o2
JSONObject mergedObj = new JSONObject();
Iterator i1 = o1.keys();
Iterator i2 = o2.keys();
String tmp_key;
while(i1.hasNext()) {
tmp_key = (String) i1.next();
mergedObj.put(tmp_key, o1.get(tmp_key));
}
while(i2.hasNext()) {
tmp_key = (String) i2.next();
mergedObj.put(tmp_key, o2.get(tmp_key));
}
Now, the merged JSONObject is stored in mergedObj
json objects to be merge in that new json object like this.
JSONObject jObj = new JSONObject();
jObj.put("one", "1");
jObj.put("two", "2");
JSONObject jObj2 = new JSONObject();
jObj2.put("three", "3");
jObj2.put("four", "4");
JSONParser p = new JSONParser();
net.minidev.json.JSONObject o1 = (net.minidev.json.JSONObject) p
.parse(jObj.toString());
net.minidev.json.JSONObject o2 = (net.minidev.json.JSONObject) p
.parse(jObj2.toString());
o1.merge(o2);
Log.print(o1.toJSONString());
now o1 will be the merged json object.
you will get the output like this ::
{"three":"3","two":"2","four":"4","one":"1"}
please refer this link and download the smartjson library ..here is the link http://code.google.com/p/json-smart/wiki/MergeSample
hope it will help.
How about this:
Iterator iterator = json2.keys();
while(iterator.hasNext()){
String key = iterator.next().toString();
json1.put(key,map.optJSONObject(key));
}
Merge JsonObject(gson)-
JsonObject data = new JsonObject();
data = receivedJsoData.get("details").getAsJsonObject();
JsonObject data2 = new JsonObject();
data2 = receivedJsoData1.get("details").getAsJsonObject();
JsonObject mergedData = new JsonObject();
Set<Map.Entry<String, JsonElement>> entries = data1.entrySet(); //will return members of your object
for (Map.Entry<String, JsonElement> entry : entries) {
mergedData.add(entry.getKey(), entry.getValue());
}
Set<Map.Entry<String, JsonElement>> entries1 = data2.entrySet(); //will return members of your object
for (Map.Entry<String, JsonElement> entry : entries1) {
mergedData.add(entry.getKey(), entry.getValue());
}
Try this.. hope it helps
JSONObject result = new JSONObject();
result.putAll(o1);
result.putAll(O2);