How to get value from Map key in java - java

I am trying to receive message attributes from Amazon SQS with the following code :
Map<String, com.amazonaws.services.sqs.model.MessageAttributeValue> attributes = new HashMap<String, com.amazonaws.services.sqs.model.MessageAttributeValue>();
attributes = message.getMessageAttributes();
for(String key: attributes.keySet()){
System.out.println(key + " - "+ attributes.get(key));
}
and it returns the output:
project - {StringValue: 25,StringListValues: [],BinaryListValues: [],DataType: String}
I want to get only the value 25. How do I do that?

Try this:
attributes.get("project").getStringValue()
References:
How to extract from a Map the value of a given key?
How to extract a String Value of a given MessageAttributeValue?

Because that's the object of value type com.amazonaws.services.sqs.model.MessageAttributeValue declared in your Map .
You need to get the value out of that object like the way you would normally do :
for(String key: attributes.keySet()){
com.amazonaws.services.sqs.model.MessageAttributeValue object = attributes.get(key);
//some method to get that 25 value
System.out.println(key + " - "+ object.getStringValue());
}

You need to loop on your map here is an example to show you how to get the values of the map:
I have a : Map<String, Object> map = new HashMap<String, Object>();
for (Entry<String, Object> entry : map.entrySet()) {
System.out.println("entry key : "+entry.getKey());
System.out.println("Object value :"+entry.getValue());
}

use this (library org.json.JSONObject; [java-json.jar])
Map<String, com.amazonaws.services.sqs.model.MessageAttributeValue> attributes = new HashMap<String, com.amazonaws.services.sqs.model.MessageAttributeValue>();
attributes = message.getMessageAttributes();
for(String key: attributes.keySet()){
System.out.println(key + " - "+ attributes.get(key));
try {
JSONObject json = new JSONObject(attributes.get(key));
System.out.println(json.get("StringValue"));
} catch (JSONException e) {
e.printStackTrace();
}
}

Related

Map string arraylist getting key and value

From the API response, I'm parsing the JSON
String myData = jsonSlurper.parseText(responseBody)
Map parsedBiblio = jsonSlurper.parseText(myData)
below is the output of parsedBiblio
{"Data": {"AppNumber": "15671037", "CustomerNumber": "81744", "Date": "08-07-2017", "Status": "Active"},
"Applicants": [{"Name": "abcd Inc.", "Address": "xxx, CA (US)"}],
below is the code of retrieving the Data key and corresponding value
Map<Object, Object> innerMap = parsedBiblio.get("Data")
for (Object objectName : innerMap.keySet()) {
println("Key: " + objectName + " Value: "+ innerMap.get(objectName) +".");
}
Let me know how I can retrieve the Applicants key and the corresponding values, because this is map<string,List<string> format, so I will declare the innermap in the below format
Map<String, List<String>> innerMapApplicant = parsedBiblio.get("Applicants")
I get this error
Cannot cast object '[{Address=xxx, CA (US), Name=abcd Inc.}]' with class 'java.util.ArrayList' to class 'java.util.Map' due to: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.util.Map(groovy.json.internal.LazyMap)
I think you should try retrieving Applicant as follow:
List<Map<String,String>> applicantList = = parsedBiblio.get("Applicants")
You can fetch key and value in the map as follow :
for(Map<String,String> applicantMap: applicantList)
{
for (Object objectName : applicantMap.keySet())
{
println("Key: " + objectName + " Value: "+ applicantMap.get(objectName) +".");
}
}
Don't understand why you double parse a String
If responseBody is an string, you can write:
def json = jsonSlurper.parseText(responseBody)
println json.Data.Applicants.Name
println json.Data.Applicants.Address

How do you parse JSON object keys as integers with Jackson?

I am deserializing a JSON into a Map<Integer, String>.
But I am getting the above classCastException if I try to assign a key to primitive int .
ObjectReader reader = new ObjectMapper().reader(Map.class);
String patternMetadata = "{\"1\":\"name\", \"2\":\"phone\", \"3\":\"query\"}";
Map<Integer, String> map = reader.readValue(patternMetadata);
System.out.println("map: " + map);
for (Map.Entry<Integer, String> entry : map.entrySet())
{
try
{
System.out.println("map: " + entry.getKey());
int index = entry.getKey();
System.out.println("map**: " + index);
}
catch (Exception e)
{
e.printStackTrace();
}
}
I am getting this java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer exception on second line in try block.
I even tried changing int index = enty.getKey().intValue(). But still the same exception occurs.
P.S.: I am running it in an Android studio using Robolectric framework.
Those keys aren't integers, they're strings. Note the quotes on them:
String patternMetadata = "{\"1\":\"name\", \"2\":\"phone\", \"3\":\"query\"}";
// ------------------------^^-^^-----------^^-^^------------^^-^^
If this is JSON (it seems to be), object property names are always strings.
You'll need a Map<String, String> and then you'll need to parse the keys to int explicitly (if needed).
Jackson can deserialize keys into some default types (or custom types with some extra configuration) if you tell it to.
Since Map is a generic type, you'll need to use a TypeReference to describe the parameterization you want.
reader is deprecated since 2.5. You should use readerFor instead. Construct your ObjectReader by providing an appropriate TypeReference with Integer keys for the Map. Jackson will then know you expect Integer values as the keys to your map.
ObjectReader reader = new ObjectMapper().readerFor(new TypeReference<Map<Integer, String>>() {
});
Full example
ObjectReader reader = new ObjectMapper().readerFor(new TypeReference<Map<Integer, String>>() {
});
String patternMetadata = "{\"1\":\"name\", \"2\":\"phone\", \"3\":\"query\"}";
Map<Integer, String> map = reader.readValue(patternMetadata);
System.out.println("map: " + map);
for (Map.Entry<Integer, String> entry : map.entrySet()) {
try {
System.out.println("map: " + entry.getKey());
int index = entry.getKey();
System.out.println("map**: " + index);
} catch (Exception e) {
e.printStackTrace();
}
}
prints
map: {1=name, 2=phone, 3=query}
map: 1
map**: 1
map: 2
map**: 2
map: 3
map**: 3

How can i fetch all data present in Map<String,Map<String,String>> data structure?

i want to retrieve all data that are present in my data structure, which is of type Map of Maps.The data structure is mentioned below.
public static Map<String, Map<String, String>> hourlyMap = new HashMap<String, Map<String, String>>();
i need all the data that are stored in the map irrespective of key.
This may help you
Map<String,Map<String,String>> hourlyMap = new HashMap<String,Map<String,String>>();
for(Map<String,String> i:hourlyMap.values()){
// now i is a Map<String,String>
for(String str:i.values()){
// now str is a value of map i
System.out.println(str);
}
}
Try:
Set<String> allData = new HashSet<>(); // will contain all the values
for(Map<String, String> map : hourlyMap.values()) {
allData.addAll(map.values());
}
for (String outerKey: hourlyMap.keySet()) {
// outerKey holds the Key of the outer map
// the value will be the inner map - hourlyMap.get(outerKey)
System.out.println("Outer key: " + outerKey);
for (String innerKey: hourlyMap.get(outerKey).keySet()) {
// innerKey holds the Key of the inner map
System.out.println("Inner key: " + innerKey);
System.out.println("Inner value:" + hourlyMap.get(outerKey).get(innerKey));
}
}

How can I get a column of value from hashmap

I have a hashmap listview with four key and multiple value that retrieve from database. For now I can get all the value from the key of FOODID2, FOODNAME2, PRICE2, RATING2 and display via toast. But what I want is just the value from the key (FOODID2) to be display. Is it possible to do it? And correct me if I'm wrong. Thanks!
for (int i=0; i<data.size(); i=i+4)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put(FOODID2, (String) data.get(i));
map.put(FOODNAME2, (String) data.get(i+1));
map.put(PRICE2, (String) data.get(i+2));
map.put(RATING2, (String) data.get(i+3));
LIST2.add(map);
for(Entry<String, String> entry: map.entrySet())
{
if(entry.getKey().equals(FOODID2))
{
Toast.makeText(getApplicationContext(),
"EXISTS " + entry.getKey(), Toast.LENGTH_LONG)
.show();
}
}
}
get entry.getKey() and just validate this
if(entry.getKey().equls("YOUR KEY NAME"))
{
// here u can print the toaste.
}
Why not just map.get(FOODID2)? That is, something like this...
StringBuilder sb = new StringBuilder();
for (HashMap<String, String> map : LIST2) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append("EXISTS " + map.get(FOODID2));
}
you can usehashMap.get(key) to get the value of a particular key.
or in your code you can use a if statement to check for the key.
You can loop map.keySet() to get all the keys, loop map.values() to get all the values.

java- how to use hashmaps for response data = a struct of keyphrases each with a single item list of the original keyphrase

I am trying to connect via an XML RPC call to an API that takes as input a list of phrases, and gives as output-- "Echoes back a struct of keyphrases each with a single item list of the original keyphrase."
I am trying to use regular hashmap parsing code in the following way--
hMap = (HashMap<String, Integer>) untypedResult;
Set set = hMap.entrySet();
Iterator i = set.iterator();
while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
resp.getWriter().println(me.getKey() + " : " + me.getValue() );
}
The output that I am getting is as follows--
Response for GetThesaurusKeyPhrases----
mp3 : [Ljava.lang.Object;#76c3358b
britney spears : [Ljava.lang.Object;#9f07597
How do I obtain the values correctly? What I think is that I should parse each value (the me.getvalue part) correctly... but I am confused on how to go about doing this... Any help would be appreciated.
You might need to cast each key and value, ie (String)me.getKey() and see what you get.
From the snippet you've posted, it is possible that the HashMap<String, Integer> in your cast is incorrect. The original HashMap may have been defined as simply a HashMap or HashMap<Object, Object> since your variable name is untypedResult. I tried the following and it works as expected:
<!-- language: lang-java -->
public static void main(String[] args) {
HashMap<String, Integer> hMap = new HashMap<String, Integer>();
hMap.put("Hi1", new Integer(1));
hMap.put("Hi2", new Integer(2));
hMap.put("Hi3", new Integer(3));
hMap.put("Hi4", new Integer(4));
Set set = hMap.entrySet();
Iterator i = set.iterator();
while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
System.out.println(me.getKey().getClass().getName() + " : " + me.getValue().getClass().getName() );
System.out.println(me.getKey() + " : " + me.getValue() );
}
}
The output for this block is:
java.lang.String : java.lang.Integer
Hi2 : 2
java.lang.String : java.lang.Integer
Hi1 : 1
java.lang.String : java.lang.Integer
Hi4 : 4
java.lang.String : java.lang.Integer
Hi3 : 3

Categories