Hashmap: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String

huangapple go评论75阅读模式
英文:

Hashmap: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String

问题

我正在尝试对我的Web应用程序进行简单的编辑,为此我从前端获取了字符串化的数据,然后将其转换为对象,但是我得到的ID是一个长整型值。我的代码在添加新数据时运行正常,但每当我尝试编辑它时都会出现错误java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String。请查看我提供的截图。

Controller.java

@RequestMapping(value = "/product", method = RequestMethod.POST)
public String managePostProduct(@RequestParam(name = "data", required = false) String add,
        @RequestParam(name = "file") MultipartFile file,
        HttpServletRequest request) {
    try {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(add);
        Addproductdetails detail = new Addproductdetails();
        OurProducts mProduct = detail.addproduct(obj, file);

        if (mProduct.getId() == 0) {
            productDAO.addOurProducts(mProduct);
        } else {
            productDAO.update(mProduct);
        }

        if (!mProduct.getFile().getOriginalFilename().equals("")) {
            FileUploadUtility.uploadFile(request, mProduct.getFile(), mProduct.getCode());
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return "redirect:/manage/product?success=product";
}

Addproductdetails.java

public OurProducts addproduct(Object obj, MultipartFile file) {
    ObjectMapper oMapper = new ObjectMapper();
    Map<String, String> prod = oMapper.convertValue(obj, HashMap.class);

    System.out.println("prod " + prod);
    OurProducts product = new OurProducts();

    if (prod.containsKey("id")) {
        System.out.println("product === " + prod.values());
    }

    int id = prod.containsKey("id") && !prod.get("id").isEmpty() ? Integer.parseInt((String) prod.get("id")) : 0;
    product.setId(id);
    product.setProduct_name(prod.get("product_name"));
    product.setProduct_info(prod.get("product_info"));
    product.setFile(file);
    return product;
}

请告诉我为什么我得到的ID是长整型值?如何修复它?

英文:

I am trying to do simple edit for my web application for that i am getting stringify data from frontend, so i converted it into object but then i am getting id as Long value.my code works fine with add new data but whenever i tried to edit it gives error
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String.
Please check the screenshot i provided.

Controller.java

	@RequestMapping(value = &quot;/product&quot;, method = RequestMethod.POST)
public String managePostProduct(@RequestParam(name = &quot;data&quot;, required = false) String add,
	 	@RequestParam(name = &quot;file&quot;) MultipartFile file,
	 	HttpServletRequest request) {
	try {
		JSONParser parser = new JSONParser();
		Object obj = parser.parse(add);
		Addproductdetails detail = new Addproductdetails();
		OurProducts mProduct = detail.addproduct(obj, file);

		if (mProduct.getId() == 0) {

			productDAO.addOurProducts(mProduct);

		} else {
			productDAO.update(mProduct);
		}

		if (!mProduct.getFile().getOriginalFilename().equals(&quot;&quot;)) {
			FileUploadUtility.uploadFile(request, mProduct.getFile(), mProduct.getCode());
		}
	} catch (ParseException e) {
		e.printStackTrace();
	}
	return &quot;redirect:/manage/product?success=product&quot;;
}

Addproductdetails,java

	public OurProducts addproduct(Object obj , MultipartFile file) {
    ObjectMapper oMapper = new ObjectMapper();
	Map&lt;String, String&gt; prod = oMapper.convertValue(obj, HashMap.class);

	System.out.println(&quot;prod &quot;+ prod);
	OurProducts product = new OurProducts();

	if (prod.containsKey(&quot;id&quot;)) {			
		System.out.println(&quot;product === &quot; + prod.values());
	}
	
	int id = prod.containsKey(&quot;id&quot;) &amp;&amp; !prod.get(&quot;id&quot;).isEmpty() ? Integer.parseInt((String) prod.get(&quot;id&quot;)) : 0;
	product.setId(id);
	product.setProduct_name(prod.get(&quot;product_name&quot;));
	product.setProduct_info(prod.get(&quot;product_info&quot;));
	product.setFile(file);
	return product;	
}

breakpoints

Hashmap: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String

please tell me why i am getting id as Long value? How can i fix it?

答案1

得分: 2

你从客户端获取了一个类型为 Longid 字段,并尝试将其放入一个 int 类型中。
如果你可以修改 Product 类,我建议将其 id 字段类型更改为 long,这样就不需要进行类型转换,同时在将 long 转换为 int 时可能会面临数据丢失的问题。

顺便提一下,如果你无法修改代码或不想修改,你可以通过以下方式解决这个问题:

将这段代码:

int id = prod.containsKey("id") && !prod.get("id").isEmpty() ? Integer.parseInt((String) prod.get("id")) : 0;

替换为:

int id = prod.containsKey("id") && !prod.get("id").isEmpty() ? (int) prod.get("id") : 0;

祝你好运。

英文:

You are getting id field from client with type of Long and trying to put it into an int type.
If you can change Product class, I recommend to change its id field type to long so that no casting is needed also you might face data loss in casting long to int.

by the way if you can not change your code or don't want to, here you can fix the problem:

instead of:

int id = prod.containsKey(&quot;id&quot;) &amp;&amp; !prod.get(&quot;id&quot;).isEmpty() ? Integer.parseInt((String) prod.get(&quot;id&quot;)) : 0;

use this:

int id = prod.containsKey(&quot;id&quot;) &amp;&amp; !prod.get(&quot;id&quot;).isEmpty() ? (int) prod.get(&quot;id&quot;) : 0;

good luck

huangapple
  • 本文由 发表于 2020年8月20日 17:02:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63501741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定