我有这种格式的字符串(包括大括号):
if let _ = answers.filter( { $0.title == (sender as AnyObject).currentTitle) }).first {
PickQuestion()
} else{
missedWords.append(quizLabel.text!)
}
表示此String的适当Java对象是什么,以及如何将其转换为该对象?
我希望能够轻松查询对象以检索其值,例如。 {id=123, vehicle_name=Tesla Model X, price=80000.00, ... }
。我尝试使用obj.get("vehicle_name")
将其转换为JSON,但是这需要将冒号作为键和值之间的分隔符,而不是等号。
答案 0 :(得分:0)
下面是一个简单的例子,关于如何做到: -
public class Test {
public static void main(String[] args){
String text="{id=123, vehicle_name=Tesla Model X, price=80000.00}";
text=text.replaceAll("[{}]", "");
String[] commaDelimitArray=text.split(",");
Vehicle vehicle=new Vehicle();
for(int i=0;i<commaDelimitArray.length;i++){
String[] keyValuePair=commaDelimitArray[i].split("=");
String key=keyValuePair[0].trim();
String value=keyValuePair[1].trim();
if("id".equals(key)){
vehicle.setId(value);
}
else if("vehicle_name".equals(key)){
vehicle.setVehicleName(value);
}
else if("price".equals(key)){
vehicle.setPrice(value);
}
}
System.out.println(vehicle.getId()+" |"+vehicle.getVehicleName());
}
static class Vehicle{
private String id;
private String vehicleName;
private String price;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVehicleName() {
return vehicleName;
}
public void setVehicleName(String vehicleName) {
this.vehicleName = vehicleName;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
}
答案 1 :(得分:0)
这似乎是创建Object类的一项任务。如果是这样,你想要创建这样的东西:
public class Car {
int id;
String name;
double price;
//include any other necessary variables
public Car(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
//include any other variables in constructor header and body
}
public void setID(int newID) {
id = newID;
}
public int getID() {
return id;
}
//add getters and setters for other variables in this same manner
}
请注意,您也可以创建一个不带参数的构造函数,并将变量初始化为默认值,然后使用setter方法单独设置值。
在您的主类中,您要做的是从String中提取适当的子字符串以传递给构造函数(或setter)。有很多方法可以做到这一点(你可以阅读一些方法here);我个人建议使用regular expressions and a Matcher。
答案 2 :(得分:0)
如果我有一个需要转换为对象的字符串,我会创建一个带有静态方法的类,该方法返回一个Vehicle对象。然后,您可以使用该对象执行任何操作。一些吸气剂和安装者,你应该好好去。
我已经提出了一些代码,如果我理解了你的问题,它应该按预期工作:)
有很多评论,所以这应该有助于您理解代码逻辑。
Vehicle Class是在名为createVehicle(String keyValueString)的静态方法中进行所有解析的地方。
主要班级:
import java.util.ArrayList;
import java.util.List;
public class main {
public static void main(String[] args) {
String vehicleString = "{id=123, vehicle_name=Tesla Model X, price=80000.00}";
List<Vehicle> vehicles = new ArrayList<Vehicle>();
Vehicle vehicle;
// call the static method passing the string for one vehicle
vehicle = Vehicle.createVehicle(vehicleString);
// if the id is -1, then the default constructor fired since
// there was an error when parsing the code.
if(vehicle.getId() == -1 ) {
System.out.println("Check your data buddy.");
} else {
vehicles.add(vehicle);
}
for(Vehicle v : vehicles){
System.out.println("Vehicle id: " + v.getId());
System.out.println("Vehicle name: " + v.getVehicle_name());
System.out.println("Vehicle price: " + v.getPrice());
System.out.println();
}
}
}
车辆类:
import java.math.BigDecimal;
public class Vehicle {
// declare your attributes mapped to your string
private int id;
private String vehicle_name;
private BigDecimal price;
// Start Constructor
// Default Constructor
public Vehicle() {
this.setId(-1);
this.setVehicle_name("Empty");
this.setPrice(new BigDecimal(0.00));
}
public Vehicle(int id, String vehicle_name, BigDecimal price) {
this.setId(id);
this.setVehicle_name(vehicle_name);
this.setPrice(price);
}
// End Constructor
// Start Getters and Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getVehicle_name() {
return vehicle_name;
}
public void setVehicle_name(String vehicle_name) {
this.vehicle_name = vehicle_name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
// End Getters and Setters.
// Start Methods and Functions
// Given a string returns a string array split by a "," and with
// "{}" removed.
private static String[] splitString(String keyValueString) {
String[] split;
// Clean string from unwanted values
keyValueString = keyValueString.replaceAll("[{}]", "");
split = keyValueString.split(",");
return split;
}
// Add a vehicle given a formatted string with key value pairs
public static Vehicle createVehicle(String keyValueString) {
int id = 0;
String vehicle_name = "";
BigDecimal price = null;
String[] split;
Vehicle vehicle;
split = splitString(keyValueString);
// Loop through each keyValue array
for(String keyValueJoined : split){
// split the keyValue again using the "="
String[] keyValue = keyValueJoined.split("=");
// remove white space and add to a String variable
String key = keyValue[0].trim();
String value = keyValue[1].trim();
// check which attribute you currently have and add
// to the appropriate variable
switch(key){
case "id":
id = Integer.parseInt(value);
break;
case "vehicle_name":
vehicle_name = value;
break;
case "price":
try {
price = new BigDecimal(Double.parseDouble(value));
} catch (NumberFormatException e) {
e.printStackTrace();
}
break;
default:
System.out.println("Attribute not available");
return null;
}
}
// if any of the values have not been changed then either the
// data is incomplete or inconsistent so return the default constructor.
// Can be removed or changed if you expected incomplete data. It all
// depends how you would like to handle this.
if(id == 0 || vehicle_name.equals("") || price == null){
vehicle = new Vehicle();
} else {
//System.out.println(id);
vehicle = new Vehicle(id, vehicle_name, price);
}
return vehicle;
}
// End Methods and Functions
}
给定提供的字符串,程序在使用getter访问新创建的对象属性时返回以下内容:
车辆识别码:123
车辆名称:特斯拉Model X
车辆 价格:80000
希望这有帮助。