0

I have a String in this format (including curly brackets):

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

What is the appropriate Java object to represent this String, and how can I convert it to that object?

I would like to be able to query the object to retrieve its values easily, eg. obj.get("vehicle_name"). I've tried converting it to JSON using JSONObject however this expects colons as the delimiters between keys and values, rather than the equals sign.

user2181948
  • 1,646
  • 3
  • 33
  • 60
  • 2
    Appropriate is a large word here. There are tons of "appropriate" ways of converting this set of attributes into an Object, started with a simple `Map` to actual instances of a class called `Car`. Probably the `id`-field is actually the `serialUID` of a class and it's meant to be deserialized. –  Dec 22 '16 at 22:55
  • 2
    Possible duplicate of [Java parsing string](http://stackoverflow.com/questions/4822552/java-parsing-string) – Timothy Truckle Dec 22 '16 at 22:57
  • 1
    Where did you get this string? Ideally, you'll want to modify the data source so that it outputs in a format you can more easily parse. – 4castle Dec 22 '16 at 22:57
  • why don't you declare your custom class? – Wasi Ahmad Dec 22 '16 at 23:05
  • 1
    Hint: it is very likely returned by `Map.toString()`. – xiaofeng.li Dec 22 '16 at 23:23
  • Run a regex replacement to convert it into JSON (needs quotes and needs equal signs replaced with colons, two-three regex replacements) and then use `new ObjectMapper().readValue(str, Map.class)` to get a Map. The latter might need a byte array, if so use `getBytes()` to get it. – Oleg Sklyar Dec 22 '16 at 23:39

3 Answers3

0
  • String itself is a java object.
  • Parsing String and filling up a java object is not clean.
  • You can create a java pojo Vehicle with attributeS like id, vehicle_name etc. Assuming your String will always follow a same pattern.
  • Parse the String, and fill this Vehicle pojo.

Below is just a simple example, on how to do it :-

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

    }

}
Amit Bhati
  • 5,569
  • 1
  • 24
  • 45
0

This appears to be an assignment in creating Object classes. If so, you want to create something like this:

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
}

Note that you could alternatively create a constructor that takes no parameters and initializes variables to default values, then set the values individually using the setter methods.

In your main class, what you want to do is extract the appropriate substrings from your String to pass to the constructor (or setters). There are various ways of doing this (you can read about some ways here); I would personally recommend using regular expressions and a Matcher.

Community
  • 1
  • 1
Bethany Louise
  • 646
  • 7
  • 13
0

If I had such a string which needed to be converted to an object I would create a class with a static method which returns a Vehicle object. Then you can do whatever you want with that object. A few getters and setters and you should be good to go.

I have come up with some code which should work as you expect if I have understood your question :)

There is quite a few comments so this should help you understand the code logic.

The Vehicle Class is where all parsing happens in the static method named createVehicle(String keyValueString).

The main class:

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

The Vehicle Class:

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
}

The program, given the string provided, returns the following when accessing the newly created object attributes using the getters:

Vehicle id: 123

Vehicle name: Tesla Model X

Vehicle price: 80000

Hope this helps.

David
  • 83
  • 1
  • 8