【问题标题】:Converting String to appropriate Java object将字符串转换为适当的 Java 对象
【发布时间】:2016-12-22 22:49:48
【问题描述】:

我有一个这种格式的字符串(包括大括号):

{id=123, vehicle_name=Tesla Model X, price=80000.00, ... }

什么是合适的Java对象来表示这个字符串,我怎样才能把它转换成那个对象?

我希望能够查询对象以轻松检索其值,例如。 obj.get("vehicle_name")。我尝试使用 JSONObject 将其转换为 JSON,但是这需要冒号作为键和值之间的分隔符,而不是等号。

【问题讨论】:

  • 适当在这里是一个大词。有很多“适当”的方法可以将这组属性转换为对象,从简单的Map 到称为Car 的类的实际实例。 id-field 可能实际上是一个类的 serialUID,它应该被反序列化。
  • Java parsing string的可能重复
  • 你从哪里得到这个字符串的?理想情况下,您需要修改数据源,以便它以更容易解析的格式输出。
  • 你为什么不声明你的自定义类?
  • 提示:很可能是Map.toString()返回的。

标签: java


【解决方案1】:
  • String 本身是一个 java 对象。
  • 解析字符串并填充 java 对象不干净。
  • 您可以创建一个 java pojo Vehicle,其属性如 id, 车辆名称等。假设您的字符串将始终遵循相同的 模式。
  • 解析字符串,并填写此 Vehicle pojo。

下面只是一个简单的例子,关于如何做到这一点:-

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;
        }

    }

}

【讨论】:

    【解决方案2】:

    这似乎是创建 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

    【讨论】:

      【解决方案3】:

      如果我有这样一个需要转换为对象的字符串,我将创建一个具有返回 Vehicle 对象的静态方法的类。然后你可以对那个对象做任何你想做的事情。几个 getter 和 setter 就可以了。

      如果我理解了您的问题,我已经提出了一些代码,它应该可以按您的预期工作:)

      有很多 cmets,所以这应该可以帮助您理解代码逻辑。

      Vehicle 类是在名为 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

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-30
        • 2015-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多