将Json对象转换为Java对象

时间:2014-12-25 14:47:11

标签: java json

json文件中的值是75.38,我写了一个代码来解析eclipse中的那个值:

 double legacyPremium = (double) object.get("legacyPremium");

我得到错误:

Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double at com.domain.project.Class.main(Class.java:56)

Json文件是:

{  
    "elementaryProductId":1,
    "bonusMalus":5,
    "deductible":100,
    "comprehensive":1,
    "partial":0,
    "legacyPremium":75.38,
    "product":{  
        "productId":2,
        "garage":"true",
        "constructionYear":2005,
        "region":"East",
        "dateOfBirthYoungest":"1999-06-22",
        "objectValue":30000,
        "type":"Car",
        "insuredObject":{  
            "name":"Car",
            "ownersName":"Jelena",
            "mileage":300000,
            "engineCapacity":210
        },
        "salesProduct":{  
            "salesProductId":3,
            "currency":"EUR",
            "contractStart":"2013-01-01",
            "contractEnd":"2014-01-01"
        },
        "productType":"Car"
    }
},

有人知道这是什么问题吗?

2 个答案:

答案 0 :(得分:0)

尝试使用

double x = Double.valueOf(object.get("x").toString());

而不是

double x = (double) object.get("x");

这将使您免于施放问题。考虑到字符串必须是Double类型。

答案 1 :(得分:0)

如果您可以选择,我会建议使用Google GSON代替Google json-simple。使用该库,您可以创建一个类似于您希望json表示和读取它的类,并将其转换为两行代码中的对象。我在下面给出了一个例子:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import com.google.gson.Gson;

public class Main {


    public static void main(String[] args) throws IOException{
        //Read file into a String
        BufferedReader reader = new BufferedReader(new FileReader(new File("file.json")));
        StringBuilder builder = new StringBuilder();
        String line;
        while((line= reader.readLine()) != null){
            builder.append(line);
        }
        reader.close();
        String jsonAsString = builder.toString();

        //Convert String into an MyClass Object
        Gson gson = new Gson();
        MyClass[] myClass = gson.fromJson(jsonAsString, MyClass[].class);//If your json outermost element is an array use this.


        System.out.println("elementaryProductId = " + myClass[0].elementaryProductId);
        System.out.println("productId = " + myClass[0].product.productId);
    }

    public class MyClass {
        public int elementaryProductId;
        public int bonusMalus;
        public int deductible;
        public int partial;
        public double legacyPremium;
        public Product product;
    }

    public class Product {
        public int productId;
        public boolean garage;
        public int constructionYear;
        public String region;
        public String dateOfBirthYoungest;
        public InsuredObject insuredObject;
        public SalesProduct salesProduct;
    }

    public class InsuredObject {

    }

    public class SalesProduct{

    }
}

请注意,这些字段不必公开! 这称为反序列化