Convert data in List JsonNode to Map String String in Java

0 votes
My List<JsonNode> has below data :

[{"Field1: " : "test1" , "Field2" : "test2", "Field3 " : "test3},

{""Field1: " : "t1" , "Field2" : "t2", "Field3 " : "t3},

{"Field1: " : "tt1" , "Field2" : "tt2", "Field3 " : "tt3}]

In Java, I want to conver this in to Map<String , String> format.

Could someone pelase help me.
Apr 7, 2020 in Java by Jyra
• 580 points
11,837 views

1 answer to this question.

+1 vote

Hi, @Jyra,

Basically, you can use the object mapper to convert the value for you:

ObjectMapper mapper = new ObjectMapper(); 
Map<String, Object> result = mapper.convertValue(jsonNode, new TypeReference<Map<String, Object>>(){});


If you want to be a good Java programmer, then enroll today with our Java certification course.

answered Apr 7, 2020 by Gitika
• 65,850 points
Thanks Gitika..Used it , but seeing errors.

public static HashMap<String,String> getJsonAsMap(List<JsonNode> inputs)
{
try{
ObjectMapper mapper = new ObjectMapper();
//JsonNode listNode = mapper.valueTo Tree(inputs);
HashMap<String, String> result  = mapper.readValue(inputs, new TypeReference<HashMap<String, String>>(){{);
return result;
}
catch (Exception e)
{
}

}
tried with ConvertValue too.

exception thrown:

Java.lang.IllegalArgumentException. Cannot deserialize instance of 'java.util.hashMap'. Out of start array token at [source :UNKNOWN, line :-1 , column:-1]

Hey, @Jyra,

Can you please update me with whole error logs because maybe it is happening due to jackson-xml file specifications.

Sure Gitika, Im working in VPN,, so i will take some time to write the cde again in system notepad and paste here. As I am seeing errors in ObjectMapping (Jackson library) methods, I tried an alternate way which is not showing any error but fetching only one record instead of 3. Will copy pate that too. Need your expertise please . At the end I have to extract these values from List<JsonNode> and pass this as input to the selenium text boxes. Thanks fr the responce.
Public void addinputtosc()
{
try{
Map<String, List<JsonNode>> testrecords = null;
Map<String, String> rows = new Hashmap<String, String>();

// this function takes the input sheet , sheet name and returns data in Map<String, List<JsonNode>> format.
testrecords = fetchScenariosData("C:\\testData.xlsx", "input","inputParam");
Iterator<Enry<String, List<JsonNode>>> entries = testRecords.entrySet().iterator();
while(entries.hasNext())
{
<ap.Entry<String, List<JsonNode>> entry = entries.next();
String scenarioName = entry.getKey();
List<JsonNode> testcaseInputs = entry.getValue();
if(scenarioName.equalsIgnoreCase("Validate File"))
{
ListIterator<JsonNode> listIterator = testCaseInputs.listIterator();
while(listIterator.hasNext())
{
for JsonNoded tcinputs : testCaseInputs)
{
String keyValue = tcinputs.toString();
String newKeyValue = keyValue.replaceAll("[{}]","");
String[] keyValue1 = newKeyValue.split(",");
for (String j : keyValue1)
{
String[] keyValueorg = j.split(":");
row.put(keyValueorg[0].substring(1,keyValueorg[0].length()-1), keyValueorg[1].substring(1,keyValueorg[1].length()-1));
}
}
}
break;
}
}
}
catch (exception e)
{
e.printStackTrace();
}
}

Issue : There will 3 reocrds in testcaseInputs  <JsonNode>. All the three records are iterated, but at end the "rows" map has only one record which is iterated in the last.  What should I do, if I need all rows to be put in that rows Hashmap.

testrecords data looks something like this: [ PLease note that For each scenario like Validate File, Validate Token and Validate Data, the feild names are different. They are never same.

{Validate File =
[{"File Source Env.":"Unix","TC_ID":"tc1","File Path":"/tmp/test.dat","Date":"20190101"},
{"File Source Env.":"Unix-qa","TC_ID":"tc2","File Path":"/tmp/test1.dat","Date":"20190201"},
{"File Source Env.":"Unix-dev","TC_ID":"tc3","File Path":"/tmp/test2.dat","Date":"20190201"}]
,
Validate Token =
[{"Token Env":"test","TC_ID":"tc4","token Path":"/tmp/test.tok","DAte":"20190909"}]
,
Validate Data=
[{"Source Data":"src1.txt","Target Data":"tgt.txt","DateRun":"20190808"}]
}

In google, I found Jackson Library is the easiest way to get the Feild name and values from the list<JsonNode>. I tried that will below code, but it shows the exception. I pasted the exception the comments above.

For "Validate File" LIst<JsonNode> , how can iterate the field anmes and get their values. Could you please let meknow.

Below is the code i used for Jackson library..

ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree("...<JSON string>...");

public static JsonNode getnodeValues(List<JsonNode> testrecords )throws Exception
{
    ObjectMapper mapper = new ObjectMapper();
   //JsonNode rootNode = mapper.readTree(testrecords);
    Map<String, String> map = mapper.readValue(testrecords , Map.class);
//Map<String, String> map = mapper.readValue(json, new TypeReference<Map<String, String>>() {});
    return mapper.convertValue(objects, JsonNode.class);
}

Hi, @jyra,

It looks like the problem is that you are getting incompatible versions of jackson-core and jackson-databind

If you are working with jackson-core 2.0.5 ,  I believe at least 2.1.0 is required. So, you'll need to fix the dependencies - most likely by excluding 2.0.5 and including 2.1.0.

Related Questions In Java

0 votes
2 answers

How can I convert a String variable to a primitive int in Java

 Here are two ways illustrating this: Integer x ...READ MORE

answered Aug 20, 2019 in Java by Sirajul
• 59,170 points
1,059 views
0 votes
2 answers
0 votes
2 answers

How to convert array into list in Java?

Another workaround if you use apache commons-lang: int[] ...READ MORE

answered Aug 10, 2018 in Java by samarth295
• 2,220 points
289 views
0 votes
1 answer

Convert String type to byte[] in Java

Try using String.getBytes(). It returns a byte[] ...READ MORE

answered May 8, 2018 in Java by Rishabh
• 3,620 points
362 views
0 votes
1 answer

what are the ways in which a list can be iterated

  There are 5 ways to iterate over ...READ MORE

answered Apr 23, 2018 in Java by sharth
• 3,350 points
392 views
0 votes
2 answers

What is the difference between Set and List in java?

List is an ordered sequence of elements. ...READ MORE

answered Apr 26, 2018 in Java by Akrati
• 3,190 points
18,082 views
+1 vote
3 answers

How to convert a List to an Array in Java?

Either: Foo[] array = list.toArray(new Foo[list.size()]); or: Foo[] array = ...READ MORE

answered Aug 7, 2018 in Java by Akrati
• 3,190 points
372 views
0 votes
2 answers

Java: convert List<String> to a String

With a java 8 collector, this can ...READ MORE

answered Aug 30, 2019 in Java by Sirajul
• 59,170 points
298 views
+15 votes
25 answers

How can I convert String to JSON object in Java?

Hi @Daisy You can use Google gson  for more ...READ MORE

answered Feb 7, 2019 in Java by Suresh
• 720 points
234,581 views
+1 vote
4 answers

What is a simple way to repeat a string in java?

There is already answer wriiten using StringBuilder ...READ MORE

answered Dec 16, 2020 in Java by Rajiv
• 8,910 points
26,070 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP