来自HashMap的JSONObject - 转换为字符串失败 [英] JSONObject from HashMap - Cast to String failed
问题描述
我需要从一个自定义类的 HashMap
创建 JSONObject
toString
和一个浮点值。我尝试下面的代码希望它只是工作:
public class MyClass {
...
public String toString(){
returna nice string
}
}
HashMap< MyClass,Float> map = new HashMap< MyClass,Float>();
map.put(...);
JSONObject json = new JSONObject(map);
但我得到:
java.lang.ClassCastException:MyClass不能转换为java.lang.String
创建此 JSONObject
的最佳方法是什么?
您需要更改:
HashMap< MyClass,Float> map = new HashMap< MyClass,Float>();
HashMap< String,Float>如您所说的 自定义类的toString的HashMap,map = new HashMap< String,Float>();
<和浮动值
您尚未提及如何将值放入hashmap。
但是如果你使用自定义类的 toString
方法,那么你应该像这样:
MyClass m = new MyClass();
map.put(m.toString,123.45f);
I need to create a JSONObject
from a HashMap
of a custom class's toString
and a float value. I tried the code below hoping that it would just work:
public class MyClass {
...
public String toString() {
return "a nice string"
}
}
HashMap<MyClass,Float> map = new HashMap<MyClass,Float>();
map.put(...);
JSONObject json = new JSONObject(map);
But I get:
java.lang.ClassCastException: MyClass cannot be cast to java.lang.String
What's the best way to create this JSONObject
? Thanks.
You need to change this:
HashMap<MyClass,Float> map = new HashMap<MyClass,Float>();
with
HashMap<String,Float> map = new HashMap<String,Float>();
as you said "HashMap of a custom class's toString and a float value"
You haven't mentioned how are you putting the values into the hashmap.
But if you using toString
method of your custom class, then you should put it like :
MyClass m = new MyClass();
map.put(m.toString,123.45f);
这篇关于来自HashMap的JSONObject - 转换为字符串失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!