How to get value https://example1.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886&ip=176.9.117.35 in this script?
the first Link value https://example.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886 just does not work.
String html ="<script>function getcookie(Name){\n" +
" var search=Name+\"=\";\n" +
" if(document.cookie.length>0){\n" +
" offset=document.cookie.indexOf(search)\n" +
" if(offset!=-1){\n" +
" offset+=search.length\n" +
" end=document.cookie.indexOf(\";\",offset)\n" +
" if(end==-1){end=document.cookie.length}\n" +
" return unescape(document.cookie.substring(offset, en))\n" +
" }\n" +
" }\n" +
"}\n" +
" var player = new Playerjs({\n" +
" \"id\":\"player\",\n" +
" \"poster\":\"https://media.example.com/img/2147414277.jpg\",\n" +
" \"file\":\"[SD (480p)]https://example.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886 or https://example1.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886&ip=176.9.117.35,[HD (720р)]https://example2.com/720/2147414277.mp4?md5=GXD4cKVnM5RVY363Uxn9ww&time=1580513886 or https://exampl3.com/720/2147414277.mp4?md5=GXD4cKVnM5RVY363Uxn9ww&time=1580513886&ip=190.9.117.35\",\n" +
" \"default_quality\":\"SD (480p)\"\n" +
" });\n" +
" function PlayerjsEvents(event,id,data){\n" +
" if(event==\"start\"){\n" +
" var xhttp = new XMLHttpRequest();\n" +
" xhttp.open(\"GET\", \"stat.php?id=2147414277\", true);\n" +
" xhttp.send();\n" +
" }\n" +
" if(event==\"end\"){\n" +
" \n" +
" }\n" +
" }</script>";
Pattern p = Pattern.compile("file\"",Pattern.DOTALL);
String url = "";
for (Element element : script) {
Matcher m = p.matcher(element.data());
if (m.find()){
url = m.group(1);
}
}
System.out.println(url);
I don’t really understand how the Java Regex Pattern works. I tried to find this URL many times but I'm failed.
I would be grateful if someone will help with that or at least give me a link guide of java regex for a newbie. thx
It seems to me you are trying to extract URLs from JS code using java.
There are many regex playgrounds on the web you can try such as:
http://buildregex.com
https://regex101.com
and of course Google
Search.
For your specific case :
import java.util.*;
import java.util.regex.*;
import java.net.*;
public class HelloWorld{
public static void main(String []args){
System.out.println("Hello World");
String jsCode ="<script>function getcookie(Name){\n" +
" var search=Name+\"=\";\n" +
" if(document.cookie.length>0){\n" +
" offset=document.cookie.indexOf(search)\n" +
" if(offset!=-1){\n" +
" offset+=search.length\n" +
" end=document.cookie.indexOf(\";\",offset)\n" +
" if(end==-1){end=document.cookie.length}\n" +
" return unescape(document.cookie.substring(offset, en))\n" +
" }\n" +
" }\n" +
"}\n" +
" var player = new Playerjs({\n" +
" \"id\":\"player\",\n" +
" \"poster\":\"https://media.example.com/img/2147414277.jpg\",\n" +
" \"file\":\"[SD (480p)]https://example.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886 or https://example1.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886&ip=176.9.117.35,[HD (720р)]https://example2.com/720/2147414277.mp4?md5=GXD4cKVnM5RVY363Uxn9ww&time=1580513886 or https://exampl3.com/720/2147414277.mp4?md5=GXD4cKVnM5RVY363Uxn9ww&time=1580513886&ip=190.9.117.35\",\n" +
" \"default_quality\":\"SD (480p)\"\n" +
" });\n" +
" function PlayerjsEvents(event,id,data){\n" +
" if(event==\"start\"){\n" +
" var xhttp = new XMLHttpRequest();\n" +
" xhttp.open(\"GET\", \"stat.php?id=2147414277\", true);\n" +
" xhttp.send();\n" +
" }\n" +
" if(event==\"end\"){\n" +
" \n" +
" }\n" +
" }</script>";
List<String> urls = new ArrayList<String>();
String myUrlPattern = "((https?|file):((//)|(\\\\))+[\\w\\d:##%/;$()~_?\\+-=\\\\\\.&]*)";
Pattern p = Pattern.compile(myUrlPattern);
Matcher m = p.matcher(jsCode);
while (m.find()) {
urls.add(m.group());
}
for(String s: urls)
System.out.println(s);
}
}
Gives out:
https://media.example.com/img/2147414277.jpg
https://example.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886
https://example1.com/2147414277.mp4?md5=OFvyZ55egHb4A5hUZJvSEQ&time=1580513886&ip=176.9.117.35,
https://example2.com/720/2147414277.mp4?md5=GXD4cKVnM5RVY363Uxn9ww&time=1580513886
https://exampl3.com/720/2147414277.mp4?md5=GXD4cKVnM5RVY363Uxn9ww&time=1580513886&ip=190.9.117.35
Hope this helps!
Related
This question already has an answer here:
Add item to arraylist if it does not already exist in list
(1 answer)
Closed last year.
This post was edited and submitted for review last year and failed to reopen the post:
Original close reason(s) were not resolved
Below is the sample code
String jsonString = "{\n" +
" \"models\":[\n" +
" {\n" +
" \"model\":{\n" +
" \"code\":\"ALL\",\n" +
" \"type\":null,\n" +
" \"name\":\"ALL\",\n" +
" \"feature_types\":null\n" +
" }\n" +
" },\n" +
" {\n" +
" \"model\":{\n" +
" \"code\":\"102e\",\n" +
" \"defaultLookup\":\"false\",\n" +
" \"type\":\"SIT\",\n" +
" \"name\":\"MUSTANG\",\n" +
" \"feature_types\":[\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"A\",\n" +
" \"desc\":\"All feature types\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"B\",\n" +
" \"desc\":\"Series\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"C\",\n" +
" \"desc\":\"BodyStyle\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" },\n" +
" {\n" +
" \"model\":{\n" +
" \"code\":\"980p\",\n" +
" \"defaultLookup\":\"false\",\n" +
" \"type\":\"SIT\",\n" +
" \"name\":\"Ranger\",\n" +
" \"feature_types\":[\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"C\",\n" +
" \"desc\":\"All feature types\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"D\",\n" +
" \"desc\":\"Series\"\n" +
" }\n" +
" } \n" +
" ]\n" +
" }\n" +
" },\n" +
" {\n" +
" \"model\":{\n" +
" \"code\":\"kkpou\",\n" +
" \"defaultLookup\":\"false\",\n" +
" \"type\":\"UAT\",\n" +
" \"name\":\"Transit Custom\",\n" +
" \"feature_types\":[\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"F\",\n" +
" \"desc\":\"All feature types\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"G\",\n" +
" \"desc\":\"Series\"\n" +
" }\n" +
" },\n" +
" {\n" +
" \"feature_type\":{\n" +
" \"code\":\"H\",\n" +
" \"desc\":\"Payload\"\n" +
" }\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
" ]\n" +
"}";
for(int i = 0; i<myData.size();i++)
{
String type = "SIT";
FeaturedItems item = resultList.stream().filter(featureItem -> type != null && type.equals(featureItem.getType())).findFirst().orElse(null);
if (type != null) {
item = FeaturedItems.builder().type(type).items(new ArrayList<>()).build();
resultList.add(item);//if the item already exists in the list don't add the new item, instead just add the elements in the exisiting item.
//tried the below commented code to add the item if it doesn't contain in the list -- start
/*boolean flagFound = false;
for (FeaturedItems featureItem : resultList) {
if (featureItem.getType().equalsIgnoreCase(type)) {
flagFound = true;
break;
}
}
if(!flagFound) resultList.add(item);*/
//tried the above commented code to add the item if it doesn't contain in the list -- End
for (int count = 0; count < features.size(); count++) {
String id = getFid(count);
MyDataBuild build = ....//logic to set values in the properties
item.getItems().add(build);
}
}
}
lookUpData.setFeatureGroups(resultList);
}
}
If the type value is already defined in the defined featureItems, then instead of creating the new object in the featureItems list, i need to add the unique items(desc,id) to the existing items element for the matching type. The code snippet mentioned above doesn't add the elements to the existing items if the type is matching in the featureItems list, instead it is creating the new element as shown in the output json sample.
Using a Map instead will make your live much easier. However your example is missing some data so it's a bit hard to understand what is actually happening in your code. So I can give you only a simple example for the usage.
Map<String, FeaturedItems> resultMap = new HashMap<>();
// Get the FeaturedItems for the given type. If none is present create a new one.
FeaturedItems items = resultMap.computeIfAbsent(type, k -> FeaturedItems.builder().type(k).items(new ArrayList<>()).build());
// Add your item to the list
Sale newItem // Obtain new item
items.getItems().add(newItem);
I have the following data, which is a list of lists:
"segmentation": [[239.97,260.24,222.04,270.49,199.84,253.41,213.5,227.79,259.62,200.46,274.13,202.17,277.55,210.71,249.37,253.41,237.41,264.51,242.54,261.95,228.87,271.34]]
What I need to do is to parse the information to a JSON object without removing the second braces.
I tried it with Jackson, but this fails with any data types.
Do you have any idea how to handle this?
Parse to JsonNode will work. I think u try with invalid json. check:
String value = "{\n" +
" \"segmentation\": [\n" +
" [\n" +
" 239.97,\n" +
" 260.24,\n" +
" 222.04,\n" +
" 270.49,\n" +
" 199.84,\n" +
" 253.41,\n" +
" 213.5,\n" +
" 227.79,\n" +
" 259.62,\n" +
" 200.46,\n" +
" 274.13,\n" +
" 202.17,\n" +
" 277.55,\n" +
" 210.71,\n" +
" 249.37,\n" +
" 253.41,\n" +
" 237.41,\n" +
" 264.51,\n" +
" 242.54,\n" +
" 261.95,\n" +
" 228.87,\n" +
" 271.34\n" +
" ]\n" +
" ]\n" +
"}";
JsonNode jsonNode = new ObjectMapper().readTree(value);
I have since updated this code per suggestions for this forum. I am still confused as to how to get my .txt file selection to out print all instances of the name entered. my file in which all my .txt files are contained is named, namesbystate. To access this and all instances of the names entered are where I am getting issues. I am wondering if I replace myFile with namesbystate as a pathway extension or not?
package babynamestatesocial;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class BabyNameStateSocial {
private Scanner x;
public static void main(String[] args) throws FileNotFoundException {
// Scanner variable set up to intake user input for state selection and person's name
Scanner scan = new Scanner(System.in);
System.out.println("Available state files are: \n" +
"AK " + "AL " + "AR " + "AZ " + "CA " + "CO " + "\n" +
"CT " + "DC " + "DE " + "FL " + "GA " + "HI " + "\n" +
"IA " + "ID " + "IL " + "IN " + "KS " + "KY " + "\n" +
"LA " + "MA " + "MD " + "ME " + "MI " + "MN " + "\n" +
"MO " + "MS " + "MT " + "NC " + "ND " + "NE " + "\n" +
"NH " + "NJ " + "NM " + "NV " + "NY " + "OH " + "\n" +
"OK " + "OR " + "PA " + "RI " + "SC " + "SD " + "\n" +
"TN " + "TX " + "UT " + "VA " + "VT " + "WA " + "\n" +
"WI " + "WV " + "WY " + "\n");
System.out.print("Enter a state to read names from: " + "\n");
String filename = scan.nextLine() + ".txt";
System.out.println("Which name would you like to look up?");
String personName = scan.nextLine();
File myFile = new File(filename);
openFile(myFile,personName);
}
private static void openFile(File myFile, String personName){
try {
Scanner sc = new Scanner(myFile);
while (sc.hasNext()) {
// nextLine variable now has the line from the file in it that matches the name the person input
String nextLine = sc.nextLine();
if (nextLine.contains(personName)) {
}
}
} catch(FileNotFoundException e) {
System.out.print(e.getMessage());
}
}
}
Something like this will get you to where you want to be. I do not have the format of your state text files so I couldn't write the full program for you
(Edit - I just changed the code slightly. Instead of sc.next(), I should have written sc.nextLine(). The following program runs successfully with that edit):
package babynamestatesocial;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class BabyNameStateSocial {
private Scanner x;
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println("Available state files are: \n" +
"AK " + "AL " + "AR " + "AZ " + "CA " + "CO " + "\n" +
"CT " + "DC " + "DE " + "FL " + "GA " + "HI " + "\n" +
"IA " + "ID " + "IL " + "IN " + "KS " + "KY " + "\n" +
"LA " + "MA " + "MD " + "ME " + "MI " + "MN " + "\n" +
"MO " + "MS " + "MT " + "NC " + "ND " + "NE " + "\n" +
"NH " + "NJ " + "NM " + "NV " + "NY " + "OH " + "\n" +
"OK " + "OR " + "PA " + "RI " + "SC " + "SD " + "\n" +
"TN " + "TX " + "UT " + "VA " + "VT " + "WA " + "\n" +
"WI " + "WV " + "WY " + "\n");
System.out.print("Enter a state to read names from: " + "\n");
String filename = scan.nextLine() + ".txt";
System.out.println("Which name would you like to look up?");
String personName = scan.nextLine();
File myFile = new File(filename);
openFile(myFile,personName);
}
private static void openFile(File myFile, String personName){
try {
Scanner sc = new Scanner(myFile);
while (sc.hasNext()) {
String nextLine = sc.nextLine();
if (nextLine.contains(personName)) {
//nextLine variable now has the line from the file in it that matches the name the person input so you need to parse that line and do something with it
}
}
} catch(Exception e) {
System.out.print(e.getMessage());
}
}
}
I am trying to drag & drop 2 elements into my workspace but they are dropped over each other, how can i specify the position of dropping the elements?
I am using dragAndDrop() function
Actions act=new Actions(driver);
act.dragAndDrop(From, To).build().perform();
enter image description here
Using dragAndDrop() method you can perform drag and drop operations on only one location at a time. it is usually used to perform operations on web element which is capable of dropping. please find the reference http://demoqa.com/droppable/ for various types of dropable elements.
To implement drag and drop operation -
Example:
WebElement From=driver.findElement(By.xpath( <<source xpath>> ));
WebElement To=driver.findElement(By.xpath( <<destination xpath>> ));
Actions actions=new Actions(driver);
actions.dragAndDrop(From, To).build().perform();
to drag and drop another element, you need to perform above all steps again.
Hope this helps :)
Try Using below code :
public static void dragAndDropViaJQueryHelper(WebDriver driver, String dragSourceJQuerySelector, String dropTargetJQuerySelector) {
String jqueryScript = "(function( jquery ) {\r\n" +
" jquery.fn.simulateDragDrop = function(options) {\r\n" +
" return this.each(function() {\r\n" +
" new jquery.simulateDragDrop(this, options);\r\n" +
" });\r\n" +
" };\r\n" +
" jquery.simulateDragDrop = function(elem, options) {\r\n" +
" this.options = options;\r\n" +
" this.simulateEvent(elem, options);\r\n" +
" };\r\n" +
" jquery.extend(jquery.simulateDragDrop.prototype, {\r\n" +
" simulateEvent: function(elem, options) {\r\n" +
" /*Simulating drag start*/\r\n" +
" var type = 'dragstart';\r\n" +
" var event = this.createEvent(type);\r\n" +
" this.dispatchEvent(elem, type, event);\r\n" +
"\r\n" +
" /*Simulating drop*/\r\n" +
" type = 'drop';\r\n" +
" var dropEvent = this.createEvent(type, {});\r\n" +
" dropEvent.dataTransfer = event.dataTransfer;\r\n" +
" this.dispatchEvent(jquery(options.dropTarget)[0], type, dropEvent);\r\n" +
"\r\n" +
" /*Simulating drag end*/\r\n" +
" type = 'dragend';\r\n" +
" var dragEndEvent = this.createEvent(type, {});\r\n" +
" dragEndEvent.dataTransfer = event.dataTransfer;\r\n" +
" this.dispatchEvent(elem, type, dragEndEvent);\r\n" +
" },\r\n" +
" createEvent: function(type) {\r\n" +
" var event = document.createEvent(\"CustomEvent\");\r\n" +
" event.initCustomEvent(type, true, true, null);\r\n" +
" event.dataTransfer = {\r\n" +
" data: {\r\n" +
" },\r\n" +
" setData: function(type, val){\r\n" +
" this.data[type] = val;\r\n" +
" },\r\n" +
" getData: function(type){\r\n" +
" return this.data[type];\r\n" +
" }\r\n" +
" };\r\n" +
" return event;\r\n" +
" },\r\n" +
" dispatchEvent: function(elem, type, event) {\r\n" +
" if(elem.dispatchEvent) {\r\n" +
" elem.dispatchEvent(event);\r\n" +
" }else if( elem.fireEvent ) {\r\n" +
" elem.fireEvent(\"on\"+type, event);\r\n" +
" }\r\n" +
" }\r\n" +
" });\r\n" +
"})(jQuery);";
((JavascriptExecutor) driver).executeScript(jqueryScript);
String dragAndDropScript = "jQuery('" + dragSourceJQuerySelector + "').simulateDragDrop({ dropTarget: '" + dropTargetJQuerySelector + "'});";
((JavascriptExecutor) driver).executeScript(dragAndDropScript);
}
Just pass css or xpath selectors in parameters.
Hope that helps you.
If that does not help you I can help you out with some other solutions also.
I am trying to get a value from a JSON string but I am getting a null value instead.
App2.java :
package JsonExample1;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.io.StringReader;
public class App2 {
private JsonNode rootNode;
public void setup() throws IOException {
String jsonString = "{\n" +
" \"HotelListResponse\" : {\n" +
" \"customerSessionId\" : \"0ABAAA7A-90C9-7491-3FF2-7E2C37496CA2\",\n" +
" \"numberOfRoomsRequested\" : 1,\n" +
" \"moreResultsAvailable\" : true,\n" +
" \"cacheKey\" : \"7790c974:13ff7e2c374:6ccd\",\n" +
" \"cacheLocation\" : \"10.186.170.122:7300\",\n" +
" \"HotelList\" : {\n" +
" \"#activePropertyCount\" : \"223\",\n" +
" \"#size\" : \"1\",\n" +
" \"HotelSummary\" : {\n" +
" \"#order\" : \"0\",\n" +
" \"hotelId\" : 125727,\n" +
" \"name\" : \"Red Lion Hotel on Fifth Avenue\",\n" +
" \"address1\" : \"1415 5th Ave\",\n" +
" \"city\" : \"Seattle\",\n" +
" \"stateProvinceCode\" : \"WA\",\n" +
" \"postalCode\" : 98101,\n" +
" \"countryCode\" : \"US\",\n" +
" \"airportCode\" : \"SEA\",\n" +
" \"supplierType\" : \"E\",\n" +
" \"hotelRating\" : 3.5,\n" +
" \"propertyCategory\" : 1,\n" +
" \"confidenceRating\" : 90,\n" +
" \"amenityMask\" : 7847938,\n" +
" \"tripAdvisorRating\" : 4,\n" +
" \"locationDescription\" : \"Near Pike Place Market\",\n" +
" \"shortDescription\" : \"<p><b>Location. </b> <br />Red Lion Hotel on Fifth Avenue is located close to 5th Avenue Theater, Pike Place Market, and Washington State Convention & Trade Center. Additional points of interest\",\n" +
" \"highRate\" : 149,\n" +
" \"lowRate\" : 126.65,\n" +
" \"rateCurrencyCode\" : \"USD\",\n" +
" \"latitude\" : 47.60985,\n" +
" \"longitude\" : -122.33475,\n" +
" \"proximityDistance\" : 11.168453,\n" +
" \"proximityUnit\" : \"MI\",\n" +
" \"hotelInDestination\" : true,\n" +
" \"thumbNailUrl\" : \"/hotels/1000000/60000/51000/50947/50947_180_t.jpg\",\n" +
" \"deepLink\" : \"http://travel.ian.com/index.jsp?pageName=hotAvail&cid=55505&hotelID=125727&mode=2&numberOfRooms=1&room-0-adult-total=2&room-0-child-total=0&arrivalMonth=8&arrivalDay=4&departureMonth=8&departureDay=5&showInfo=true&locale=en_US¤cyCode=USD\",\n" +
" \"RoomRateDetailsList\" : {\n" +
" \"RoomRateDetails\" : {\n" +
" \"roomTypeCode\" : 253461,\n" +
" \"rateCode\" : 201054304,\n" +
" \"maxRoomOccupancy\" : 2,\n" +
" \"quotedRoomOccupancy\" : 2,\n" +
" \"minGuestAge\" : 0,\n" +
" \"roomDescription\" : \"Classic Single Queen\",\n" +
" \"promoId\" : 202161947,\n" +
" \"promoDescription\" : \"Summer Sale! Save 15%\",\n" +
" \"currentAllotment\" : 0,\n" +
" \"propertyAvailable\" : true,\n" +
" \"propertyRestricted\" : false,\n" +
" \"expediaPropertyId\" : 50947,\n" +
" \"rateKey\" : \"0ABAAA7A-90C9-7491-3FF2-7E2C37496CCE\",\n" +
" \"RateInfo\" : {\n" +
" \"#rateChange\" : \"false\",\n" +
" \"#promo\" : \"true\",\n" +
" \"#priceBreakdown\" : \"true\",\n" +
" \"ChargeableRateInfo\" : {\n" +
" \"#total\" : \"151.23\",\n" +
" \"#surchargeTotal\" : \"24.58\",\n" +
" \"#nightlyRateTotal\" : \"126.65\",\n" +
" \"#maxNightlyRate\" : \"126.65\",\n" +
" \"#currencyCode\" : \"USD\",\n" +
" \"#commissionableUsdTotal\" : \"126.65\",\n" +
" \"#averageRate\" : \"126.65\",\n" +
" \"#averageBaseRate\" : \"149.0\",\n" +
" \"NightlyRatesPerRoom\" : {\n" +
" \"#size\" : \"1\",\n" +
" \"NightlyRate\" : {\n" +
" \"#promo\" : \"true\",\n" +
" \"#rate\" : \"126.65\",\n" +
" \"#baseRate\" : \"149.0\"\n" +
" }\n" +
" },\n" +
" \"Surcharges\" : {\n" +
" \"#size\" : \"1\",\n" +
" \"Surcharge\" : {\n" +
" \"#amount\" : \"24.58\",\n" +
" \"#type\" : \"TaxAndServiceFee\"\n" +
" }\n" +
" }\n" +
" }\n" +
" },\n" +
" \"ValueAdds\" : {\n" +
" \"#size\" : \"1\",\n" +
" \"ValueAdd\" : {\n" +
" \"#id\" : \"2048\",\n" +
" \"description\" : \"Free Wireless Internet\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }";
rootNode = new ObjectMapper().readTree(new StringReader(jsonString));
}
//other methods
public void basicTreeModelRead()
{
//Just like DOM, our data is in a hierarchy of node (in this case, it is JsonNode)
JsonNode aField = rootNode.get("customerSessionId");
//the customerSessionId has a String value
String myString = aField.asText();
System.out.println("customerSessionId is:" + myString);
}
}
StartHere.java:
package JsonExample1;
import java.io.IOException;
public class StartHere {
public static void main(String[] args) {
App2 myApp = new App2();
try {
myApp.setup();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
myApp.basicTreeModelRead();
}
}
After debugging I found that aField value remains null.
Any ideas?
Your root node doesn't have a customerSessionId, it has a HotelListResponse. Get that first.
//other methods
public void basicTreeModelRead()
{
JsonNode innerNode = rootNode.get("HotelListResponse"); // Get the only element in the root node
// get an element in that node
JsonNode aField = innerNode.get("customerSessionId");
//the customerSessionId has a String value
String myString = aField.asText();
System.out.println("customerSessionId is:" + myString);
}
This prints
customerSessionId is:0ABAAA7A-90C9-7491-3FF2-7E2C37496CA2
Another way to get the inner element, with .at() method:
rootNode.at("/HotelListResponse/customerSessionId")
Convert to the Map
Map map = objectMapper.readValue(jsonString, Map.class);
Method for navigation in the map
private static <T> T get(Map map, Class<T> clazz, String... path) {
Map node = map;
for (int i = 0; i < path.length - 1; i++) {
node = (Map) node.get(path[i]);
}
return (T) node.get(path[path.length - 1]);
}
Usage:
String value = get(map, String.class, "path", "to", "the", "node")