简体   繁体   中英

Java parse String into java Object

How can I parse a String like:

String m = "Material: chair\nPrice: 302.91\nCount: 5"

into a java Object:

public class Order {
    String material;
    String price;
    int count;
}

A very trivial solution is:

public class Main {
    public static void main(String[] args) {
        String m = "Material: chair\nPrice: 302.91\nCount: 5";
        Order order = new Order(m);
        System.out.println(order.count);
        System.out.println(order.material);
        System.out.println(order.price);
    }
}


class Order {
    String material;
    String price;
    int count;
    public Order(String str){
        String[] parsedArr = str.split("\n");
        String materialStr = parsedArr[0];
        String priceStr = parsedArr[1];
        String countStr = parsedArr[2];
        this.material = materialStr.split(":")[1].trim();
        this.price = priceStr.split(":")[1].trim();
        this.count = Integer.parseInt(countStr.split(":")[1].trim());
    }
}

Just like other answers. I would recommend to use JSON instead of this kind of random String.

Simply create a class:

class Material{
    String material;
    String price;
    int count;
    public Material(String material, String price, int count){
         this.material = material;
         this.price = price;
         this.count = count;
    }
    // Override toString()? Comparable (compareTo())? 
}
class Foo{
    public static void main (String[] args){
         String S = "Wood 50 10";
         Material m = new Material();
         //m is now an object
         // You want to parse a string into an object. One way is java.util.Scanner
         // with methods like Scanner.nextInt() and Scanner.next();
         java.util.Scanner sc = new java.util.Scanner(S);
         m = new Material(sc.next(), sc.next(), sc.nextInt());

         String[] values = S.split(" "); // Split the string into and copy to an array
         m = new Material(values[0], values[1], Integer.parseInt(values[2]));
    }
}

Ah @Pshemo said in the comments to your question, what you're trying to do is what JSON already does. For that simple purpose, JSON is extremely easy to use and will do exactly what you want, it will take a String (Properly formatted in the JSON way) and will convert it to the corresponding Object.

You have this tutorial from TutorialsPoint to get you up to pace.

When I was making a project for a faculty course last semestre, I used GSON which is JSON from Google and followed this tutorial which, IMO, is the best to follow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM