如何在Java中读取具有相同名称的多列数据

huangapple 未分类评论67阅读模式
英文:

How to read same more than one column having same name in Java

问题

Java代码

public List<Map<?, ?>> convert(String file) throws Exception {
       File input = new File(file);
       try {

          CsvSchema csv = CsvSchema.emptySchema().withHeader(); 
          CsvMapper csvMapper = new CsvMapper(); 
          MappingIterator<Map<?, ?>> mappingIterator =  csvMapper.reader().forType(Map.class).with(csv).readValues(input); 
          List<Map<?, ?>> list = mappingIterator.readAll(); 
          return list; 
      } catch(Exception e) { 
         e.printStackTrace(); 
         return null; 
      } 
   } 

期望的JSON输出

[
	{
		UserName=DasKhatri, Pass=777, Name=Guru, FamilyName=Khatri, ShortName=GK, UserName=GuruKhatri, Pass=111
	}
]

实际获得的JSON输出

[
	{
		UserName=GuruKhatri, Pass=111, Name=Guru, FamilyName=Khatri, ShortName=GK
	}
]
英文:

How to read same more than one column having same name in Java

Description:
I am converting CSV to JSON by reading csv schema and successful into it, but the problem is that the CSV file contains two column having same name, and it is overriding the second column value into first one and not showing the second column in json.

My requirement is to read both column values into json and pass on, as
The code block is below, I browsed to find a work around, yet not successful! My Application is written in java.

Code

public List&lt;Map&lt;?, ?&gt;&gt;  convert(String file) throws Exception {
       File input = new File(file);
       try {

          CsvSchema csv = CsvSchema.emptySchema().withHeader(); 
          CsvMapper csvMapper = new CsvMapper(); 
          MappingIterator&lt;Map&lt;?, ?&gt;&gt; mappingIterator =  csvMapper.reader().forType(Map.class).with(csv).readValues(input); 
          List&lt;Map&lt;?, ?&gt;&gt; list = mappingIterator.readAll(); 
          return list; 
      } catch(Exception e) { 
         e.printStackTrace(); 
         return null; 
      } 
   } 

如何在Java中读取具有相同名称的多列数据

JSON I want

[
	{
		UserName=DasKhatri, Pass=777, Name=Guru, FamilyName=Khatri, ShortName=GK, UserName=GuruKhatri, Pass=111
	}
]

JSON I am Getting

[
	{
		UserName=GuruKhatri, Pass=111, Name=Guru, FamilyName=Khatri, ShortName=GK
	}
]

huangapple
  • 本文由 发表于 2020年7月28日 21:44:35
  • 转载请务必保留本文链接:https://java.coder-hub.com/63135580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定