I have hashmap string object below. How to get value name from object SubSource.value index 0? I just found function for get first object, for example I just get value from test with hashMapValue.get("test"). How to get value object inside the object? should I convert to json and I get the value? Thanks.
{
"test" : {
"type" : "",
"value" : ""
},
"Attachment" : {
"type" : "",
"value" : ""
},
"SubSource" : {
"type" : "string",
"value" : [ {
"address" : "xxx.xxxx#xxx.co.id",
"name" : "bobby"
}, {
"address" : "xxx.xxxx#xxx.co.id",
"name" : "2sadasd"
}, {
"address" : "xxx.xxxx#xxx.co.id",
"name" : "ggfgf"
} ]
}
}
My code:
Map<String, Object> departmentPHSSuportEmail = new HashMap<String, Object>();
Map<String, Object> subSourceMap = null;
List<Map<String , Object>> myMap = new ArrayList<Map<String,Object>>();
Map<String, Object> attachment = new HashMap<String, Object>();
attachment.put("type", "");
attachment.put("value", "");
departmentPHSSuportEmail.put("Attachment", attachment);
Map<String, Object> subSource = new HashMap<String, Object>();
subSource.put("type", "string");
subSource.put("value", myMap);
departmentPHSSuportEmail.put("SubSource", subSource);
// create a fresh map
Map<String,Object> subSourceMap1 = new HashMap<>();
subSourceMap1.put("name", "bobby");
subSourceMap1.put("address", "xxx.xxxx#xxx.co.id");
// create a fresh map
Map<String,Object> subSourceMap2 = new HashMap<>();
subSourceMap2.put("name", "2sadasd");
subSourceMap2.put("address", "xxx.xxxx#xxx.co.id");
// create a fresh map
Map<String,Object> subSourceMap3 = new HashMap<>();
subSourceMap3.put("name", "ggfgf");
subSourceMap3.put("address", "xxx.xxxx#xxx.co.id");
myMap.add(subSourceMap1);
myMap.add(subSourceMap2);
myMap.add(subSourceMap3);
Map<String, Object> attachments = new HashMap<String, Object>();
attachments.put("type", "");
attachments.put("value", "dasda");
departmentPHSSuportEmail.put("test", attachments);
Not sure what you are asking, but...
A) Cast the object you are getting from the map to the Object type you are trying to grab the values out of
String name = (String) subSourceMap1.get("name");
B) Add type parameters to your map
Map<String, String> subSourceMap1 = new HashMap<String, String>();
String name = subSourceMap1.get("name");
String address = subSourceMap1.get("address");
C) If you are wondering how to get those maps out of a list
Map<String, YourObject> subSourceMap1 = myMap.get(0); //This is index 0's of your map subsource
//You can grab index's from 'myMap' that are less than myMap.size();
This is a JSON string. Find a proper JSON deserializer library and include that in your project instead of coding all this HashMap stuff.. ;)
Ie this
jackson-2-convert-object-to-from-json
Map<String, Object> subSource2 = (Map<String, Object>)departmentPHSSuportEmail.get("SubSource");
List<Map<String , Object>> myMap2 = (List<Map<String , Object>>)subSource2.get("value");
Map<String,Object> subSourceMap3 = myMap2.get(0);
String value = (String)subSourceMap3.get("value");
There are many ways how to solve this, one of solutions can be like this:
make container for member data (address + name), if the addresses
should be unique, than can be used as a key in map
make container for attachment
make container for the whole data, because of data integrity
Please, notice, I have used hashmap for members, but arraylist for attachments, if you are expecting also unique values at attachments, than you can use also hashmap with key name, then you can use it for finding
So..
Member container
public class Member {
private String name;
private String address;
public Member(String name, String address) {
super();
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
Container for attachments
public class Attachment {
String name;
String value;
public Attachment(String name, String value) {
super();
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Than container for complete data
public class DataContainer {
Map<String, Member> membersMap;
ArrayList<Attachment> attachments;
public DataContainer() {
this.membersMap = new HashMap<String, Member>();
this.attachments = new ArrayList<Attachment>();
}
public DataContainer(Map<String, Member> membersMap, ArrayList<Attachment> attachments) {
super();
this.membersMap = membersMap;
this.attachments = attachments;
}
public Map<String, Member> getMembersMap() {
return membersMap;
}
public void setMembersMap(Map<String, Member> membersMap) {
this.membersMap = membersMap;
}
public ArrayList<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(ArrayList<Attachment> attachments) {
this.attachments = attachments;
}
public void addAttachment(Attachment newItem) {
this.attachments.add(newItem);
}
public void addMember(Member newMember) {
this.membersMap.put(newMember.getAddress(), newMember);
}
public Member getMemberByAddress(String address) {
return this.membersMap.get(address);
}
}
Filling example
Map<String, Member> membersMap= new HashMap<String, Member>();
Member newMember = new Member("fooo Name", "fooo#whatever.foo");
membersMap.put(newMember.getAddress(), newMember);
Attachment newAtatchment = new Attachment("fooattach", "something");
ArrayList<Attachment> attachments = new ArrayList<>();
attachments.add(newAtatchment);
DataContainer data = new DataContainer(membersMap, attachments);
data.addMember(new Member("anotherMember", "fooo#foooo.foo"));
data.addAttachment(new Attachment("another attachmetn", "anotherAtt value"));
Related
I am writing a function that will create an object with data. So far I get objects with data but individually not as a collection. I would like to return an object with all designated data as one Student object, not just one input for every object. I tried to add objList.add(obj) out of the for loop too and outputs all null.
Here is the code
class Student{
int id;
String name;
int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
public static List<Object> createObject(Student st, List<Map<String, String>> csvStudentData) {
List<Object> objList = new ArrayList<>();
Object obj = null;
for(Map<String, String> studentData: csvStudentData) {
for (Map.Entry<String, String> entry = studentData.entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
obj = insertObjectData(st.getClass(), key, value);
objList.add(obj);
}
}
return objList;
}
You modify the method's body by the following:
public static List<Object> createObject(Student st, List<Map<String, String>> csvStudentData) {
List<Student> objList = new ArrayList<>();
for(Map<String, String> studentData: csvStudentData) {
Student student = new Student();
for (Map.Entry<String, String> entry = studentData.entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
Field field = Student.class.getDeclaredField(key);
student.set(field, value);
}
objList.add(student);
}
return objList;
}
you also add a default constructor in the class Student
You can do it in java-8 stream
List<Object> objList = csvStudentData.stream()
.flatMap(map->map.entrySet()
.stream()
.map(entry->insertObjectData(st.getClass(), entry.getKey(), entry.getValue())))
.collect(Collectors.toList());
JSON:
{
"prop":"property",
"inputInfo":{
"sku":"6157068",
"inputText":"iphone"
}
}
Code:
JSONObject inputObject = JSON.parseObject(input);
String prop = (String)inputObject.get("property");
But how to get the inner layer of 'sku' & 'inputText'?
I am using Alibaba json library in Java.
I haven't used the Alibaba library but doesn't it have a getJSONObject() method that you can use on inputObject? I have done this before but I used org.json library.
JSON:
{"circle":{
"radius":255819.07998349078,
"center":{
"lat":00.000000000000000,
"lng":00.000000000000000
}
}
}
Java
JSONObject shape = new JSONObject(entity.getJsonLocation());
double latitude = shape.getJSONObject("circle")
.getJSONObject("center")
.getDouble("lat");
double longitude = shape.getJSONObject("circle")
.getJSONObject("center")
.getDouble("lng");
This example for instance gets the JSON and creates a JSONObject shape. I can then get the inner json objects by calling getJSONObject() on shape.
I hope this can help you.
You can create a bean at first, for instance,
public class DemoInfo {
private String id;
private String city;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setCity(String city) {
this.city = city;
}
public String getCity() {
return city;
}
}
then,
String s = "{\"id\":\"0375\",\"city\":\"New York\"}";
DemoInfo info = JSON.parseObject(s, DemoInfo.class);
or you can use map instead.
JSON.parseObject(s, HashMap.class);
You can do it like this,
JSONObject inputInfoObject = inputObject.getJSONObject("inputInfo");
String sku = inputInfoObject.getString("sku");
String inputText = inputInfoObject.getString("inputText");
If you can use GSON the following is possible
public static void main(String[] args) throws IOException {
String json = "{\"prop\":\"property\",\"inputInfo\":{\"sku\":\"6157068\",\"inputText\":\"iphone\"}}";
Gson gson = new Gson();
HashMap<String, Object> res = gson.fromJson(json, HashMap.class);
for (Map.Entry<String, Object> entry : res.entrySet()) {
if ("inputInfo".equalsIgnoreCase(entry.getKey())) {
HashMap<String, Object> map = gson.fromJson(String.valueOf(entry.getValue()), HashMap.class);
for (Map.Entry<String, Object> child : map.entrySet()) {
System.out.println(child.getKey() + " : " + child.getValue());
}
}
}
}
And the result is
inputText : iphone
sku : 6157068.0
I know this question is kind of repetitive But still I can't get an answer.
I have 2 arraylists containing name and description respectively as
final ArrayList<String> arrayOne = new ArrayList<String>(); // containing names
final ArrayList<String> arraytwo = new ArrayList<String>(); // containing description
I need a view like
I have tried
arraytwo.add(arrayOne);
&
arrayThree.addAll(arrayOne);
arrayThree.addAll(arrayTwo);
But can't a desired arraylist.
Regards
POJO class
public class Model
{
String name;
String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
desc = desc;
}
}
For Storing to arraylist
ArrayList<Model> arrayModel = new ArrayList<Model>();
for(int i=0;i<arrayOne.size();i++)
{
Model model=new Model();
model.setName(arrayOne.get(i));
model.setDesc(arrayTwo.get(i));
arrayModel.add(model);
}
If you don't want to create POJO, try this:
List<String> nameList;
List<String> desList;
//for storing
Map<String, String> map = new HashMap<>();
for(int i=0;i<nameList.size();i++) {
map.put(nameList.get(i), desList.get(i));
}
//for retrieving
for(Map.Entry<String, String> m : map.entrySet())
String nameListItem = m.getKey();
String desListItem = m.getValue();
}
I am building a rest API using Jersey where XML and JSON outputs are allowed depending on what format client prefers(using Accept header).The service sends the below class as an output which looks like this
#XmlRootElement
public class ProjectDetails{
private List<Attachment> attachments;
private Map<String, List<Attachment>> imageCategory;
#XmlTransient
public List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
}
public Map<String, List<Attachment>> getImageCategory() {
if(attachments == null || attachments.size() == 0){
return null;
}
Map<String, List<Attachment>> map = new HashMap<String, List<Attachment>>();
for (Attachment img : attachments){
String key = img.getCategory();
if(BaseUtil.hasText(key)){
List<Attachment> values = map.get(key);
if (values == null){
values = new ArrayList<Attachment>();
}
values.add(img);
map.put(key, values);
}
}
this.imageCategory = map ;
return imageCategory;
}
public void setImageCategory(Map<String, List<Attachment>> imageCategory) {
this.imageCategory = imageCategory;
}
}
I don't want attachments field as an output so marked it with #XmlTransient rather I want to form a Map using the attachments field and send it as an output.
In case of JSON format, I am getting the correct response.But in case of XML, I am not getting any output when I hit the service.
I think it is related to this Map field because if I remove Map field and add some other field like String then I get that field in response.
Please let me know how to resolve this.
Update:
After some googling, i found XmlAdapter solution and implemented as below
public class MapAdapter extends
XmlAdapter<MapAdapter.AdaptedMap, Map<String, List<Attachment>>> {
public static class AdaptedEntry {
public String key;
public List<Attachment> value = new ArrayList<Attachment>();
}
public static class AdaptedMap {
List<AdaptedEntry> entries = new ArrayList<AdaptedEntry>();
}
#Override
public AdaptedMap marshal(Map<String, List<Attachment>> map)
throws Exception {
AdaptedMap adaptedMap = new AdaptedMap();
for (Entry<String, List<Attachment>> entry : map.entrySet()) {
AdaptedEntry adaptedEntry = new AdaptedEntry();
adaptedEntry.key = entry.getKey();
adaptedEntry.value = entry.getValue();
adaptedMap.entries.add(adaptedEntry);
}
return adaptedMap;
}
#Override
public Map<String, List<Attachment>> unmarshal(AdaptedMap adaptedMap)
throws Exception {
List<AdaptedEntry> adapatedEntries = adaptedMap.entries;
Map<String, List<Attachment>> map = new HashMap<String, List<Attachment>>(
adapatedEntries.size());
for (AdaptedEntry adaptedEntry : adapatedEntries) {
map.put(adaptedEntry.key, adaptedEntry.value);
}
return map;
}
And then
#XmlJavaTypeAdapter(MapAdapter.class)
public Map<String, String> getImageCategory() {
But still it's not working..Anything I missed?
I have used your ProjectDetails class a little bit changes I've made, and it provides response for both XML and JSON. Can you try this?
#XmlRootElement
public class ProjectDetails {
private List<Attachment> attachments;
private Map<String, ArrayList<Attachment>> imageCategory;
#XmlTransient
public List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
}
#XmlJavaTypeAdapter(MapAdapter.class)
public Map<String, ArrayList<Attachment>> getImageCategory() {
if(attachments == null || attachments.size() == 0){
return null;
}
Map<String, ArrayList<Attachment>> map = new HashMap<String, ArrayList<Attachment>>();
for (Attachment img : attachments){
String key = img.getCategory();
if(!key.equals("")){
ArrayList<Attachment> values = map.get(key);
if (values == null){
values = new ArrayList<Attachment>();
}
values.add(img);
map.put(key, values);
}
}
this.imageCategory = map ;
return imageCategory;
}
public void setImageCategory(Map<String, ArrayList<Attachment>> imageCategory) {
this.imageCategory = imageCategory;
}
}
And the Adapter class you can use the following
public class MapAdapter extends XmlAdapter<MapElement[], Map<String, ArrayList<Attachment>>>{
public MapElement[] marshal(Map<String, ArrayList<Attachment>> arg0) throws Exception {
MapElement[] mapElements = new MapElement[arg0.size()];
int i = 0;
for (Map.Entry<String, ArrayList<Attachment>> entry : arg0.entrySet()){
mapElements[i++] = new MapElement(entry.getKey(), entry.getValue());
}
return mapElements;
}
public Map<String, ArrayList<Attachment>> unmarshal(MapElement[] arg0) throws Exception {
Map<String, ArrayList<Attachment>> r = new HashMap<String, ArrayList<Attachment>>();
for (MapElement mapelement : arg0)
r.put(mapelement.key, mapelement.value);
return r;
}
}
I've changed the MapElement also
public class MapElement {
#XmlElement
public String key;
#XmlElement
public ArrayList<Attachment> value;
private MapElement() {
}
public MapElement(String key, ArrayList<Attachment> value) {
this.key = key;
this.value = value;
}
}
And the Attachement class should have getter setter methods
public class Attachment {
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
private String category;
public Attachment(String cat){
this.category = cat;
}
}
I am reading two csv files containg a set of attributes
File 1 attributes = name, class, rollno,
File 2 attributes = rollno, city,town
I need to match the two files and for every matching rollno I have to append the File 2 attributes into File1 and create a csv file in the format
rollno, name, class, city, town
So far I have succeeded in reading the File1 and file2 values into a List of linked hashmaps of the type.
List<Map<Object, Object>> _students = new ArrayList<Map<Object, Object>>();
I am not able to figure out the steps to move forward.
How do I search through the list map of first file for the roll no contained in the second listmap and append it to the firstlistmap?
and then print it to a csv file in the order specified ( I am able to iterate and print all the values in the order they were inserted in the map)
I would approach this problem by reading the first file and store the values in a hashmap. and then append to that hashmap
The key would be the role number and the value would be a list of the the other values.
Map<String, List<String>> map = new HashMap<String, List<String>>()
Pseudocode:
for (List<String> line : file1.lines) {
List curLine = new LinkedList();
curLine.add(line.get(0));
curLine.add(line.get(1));
map.put(line.get(2),curLine)
}
for (List<String> line : file2.lines) {
String key = line.get(0);
String list = map.get(key);
if (list != null)
{
list.add(line.get(1));
list.add(line.get(2));
}
map.put(key,list); // probably not necessary as you change the reference that is already in the map, but I'm not sure
}
Load the second file into a Map keyed by rollno This way you can lookup the details which match a rollno using the get() method.
Assuming, you managed to load the contents of both files into practical datastructures:
List<String[]> file1 = loadFile1(); // each item is a String array {name, class, rollNo}
List<String[]> file2 = loadFile2(); // each item is a String array {rollNo, city, town}
then create a map like this:
// sorted map
Map<String, String[]> result = new TreeMap<String, String[]>();
// create a map entry for each roll nr of first file, add name and class
for (String[] file1Item : file1) {
result.put(file1Item[0], new String[4] {file1Item[1], file2Item[2], "", ""});
}
// add the values from list 2
for (String[] file2Item : file2) {
String[] value = result.get(file2Item[2]);
if (value != null) {
value[2] = file2Item[1];
value[3] = file2Item[2];
}
}
Now you have a map like this:
rollno -> [name, class, city, town]
Try this complete code it will work
import java.util.HashMap;
import java.util.Map;
import com.csvreader.CsvReader;
public class ListMap {
public static void main(String args[]) throws Exception {
Map<String, ListMap> map = new HashMap<String, ListMap>();
CsvReader reader = null;
reader = new CsvReader("c:/list1.csv");
reader.readHeaders();
while (reader.readRecord()) {
map.put(reader.get("RollNo"), new ListMap(reader.get("RollNo"),
reader.get("Name"), reader.get("Class"),
reader.get("City"), reader.get("Town")));
}
reader = new CsvReader("c:/list2.csv");
reader.readHeaders();
while (reader.readRecord()) {
ListMap obj = map.get(reader.get("RollNo"));
if (obj != null) {
obj.setCity(reader.get("City"));
obj.setTown(reader.get("Town"));
} else {
obj = new ListMap(reader.get("RollNo"), reader.get("Name"),
reader.get("Class"), reader.get("City"), reader
.get("Town"));
}
map.put(reader.get("RollNo"), obj);
}
for (Map.Entry<String, ListMap> entry : map.entrySet()) {
ListMap obj = entry.getValue();
System.out.println(entry.getKey() + " " + obj.name + " "
+ obj.className + " " + obj.city + " " + obj.town);
}
}
private String roolNo, name, className, city, town;
public ListMap(String roolNo, String name, String className, String city,
String town) {
super();
this.roolNo = roolNo;
this.name = name;
this.className = className;
this.city = city;
this.town = town;
}
public String getRoolNo() {
return roolNo;
}
public void setRoolNo(String roolNo) {
this.roolNo = roolNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
}