2016-04-01 133 views
0

我试图转换下面的字符串,以便我可以从中获取属性。我试图得到他们的属性,然后使物体从他们的将JSON字符串转换为java中的自定义对象

[插入这些在DB {“ParkingSpaces ;;;;”:“名称; CarPlate;说明;到期日期;所有者”}, {“ParkingSpaces ;;;;”:“A5; T555; Parkingspace A5 ;;”},{“ParkingSpaces ;;;;”:“A6; T666; Parkingspace A6 ;;”},{“ParkingSpaces ;;;;” :“A7; T777; Parkingspace A7 ;;”},{“ParkingSpaces ;;;;”:“”}]

我从CSV文件中得到了这个字符串。

任何对我如何处理这个问题有想法的人?

在此先感谢。

+0

请http://stackoverflow.com/questions/15246030/json-string-to-java-对象 – Alice

+0

'{“ParkingSpaces ;;;;”:“Name; CarPlate; Description; ExpirationDate; Owner”}'是你的JSON字符串吗? – Alice

+0

@Alice是的,这是我用angular-csv-import库转换后得到的。 –

回答

0

你的代码相当混乱,但它是可行的。您可以在例如使用simple JSON parsing方法,如:

final String json = "[{\"ParkingSpaces;;;;\":\"Name;CarPlate;Description;ExpirationDate;Owner\"," 
{\"ParkingSpaces;;;;\":\"A5;T555;Parkingspace A5;;\"},{\"ParkingSpaces;;;;\":\"A6;T666;Parkingspace A6;;\"},{\"ParkingSpaces;;;;\":\"A7;T777;Parkingspace A7;;\"},{\"ParkingSpaces;;;;\":\"\"}]"; 
     final org.json.JSONArray jSONArray = new JSONArray(json); 
     for (int i = 0; i < jSONArray.length(); i++) { 
      final org.json.JSONObject jSONObject = jSONArray.getJSONObject(i); 
      final String parkingSpaces = jSONObject.getString("ParkingSpaces;;;;"); 
      final String spaces[] = parkingSpaces.split(";"); 
      System.out.println(Arrays.toString(spaces)); 
     } 
    } 

use some bindings like Jackson

+0

使用这段代码后,我能够做到我想要的,谢谢。 –

0

你有什么是JSON与一些分号分隔的字符串中。我根本不会称这为CSV格式。

您可以使用像Gson这样的JSON解析器来解析JSON到Java对象,但是您仍然需要从Java对象中选择“列”,因为它们没有在JSON中正确定义。

像这样的东西应该工作,我建议你添加更多的错误检查比我虽然:

public class DBEntry { 

    @SerializedName("ParkingSpaces;;;;") 
    @Expose 
    private String ParkingSpaces; 

    public String getParkingSpaces() { 
     return ParkingSpaces; 
    } 

    public void setParkingSpaces(String ParkingSpaces) { 
     this.ParkingSpaces = ParkingSpaces; 
    } 

} 

public static void main(String[] args) { 
    String json = "[{\"ParkingSpaces;;;;\":\"Name;CarPlate;Description;ExpirationDate;Owner\"},{\"ParkingSpaces;;;;\":\"A5;T555;Parkingspace A5;;\"},{\"ParkingSpaces;;;;\":\"A6;T666;Parkingspace A6;;\"},{\"ParkingSpaces;;;;\":\"A7;T777;Parkingspace A7;;\"},{\"ParkingSpaces;;;;\":\"\"}]"; 

    // Convert JSON to java objects using the popular Gson library 
    Gson gson = new Gson(); 
    Type collectionType = new TypeToken<ArrayList<DBEntry>>(){}.getType(); 
    List<DBEntry> results = gson.fromJson(json, collectionType); 

    boolean header = true; 
    for (DBEntry result : results) { 
     // Ignore the header and empty rows 
     if (header || result.getParkingSpaces().isEmpty()) { header = false; continue; } 

     // Grab the columns from the parking spaces string 
     String[] columns = result.getParkingSpaces().split(";"); 

     // TODO: Store this record in your database 
     System.out.println("New entry: " + StringUtils.join(columns, ", ")); 
    } 
} 
相关问题