Java中的JSON和泛型

Java中的JSON和泛型

本文介绍了Java中的JSON和泛型 - 类型安全警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据存储在Java元素中,我需要以给定的格式返回它 - JSONObject。虽然我的实现工作正常,但我仍然收到eclipse(版本:Juno Service Release 2)的警告消息:



类型安全性: (Object,Object)属于原始类型HashMap。引用通用类型HashMap应参数化



这是我的代码:

  public interface Element {...} 

public abstract class AbstractElement implements Element {...}

public final class Way extends AbstractElement {...}

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class WayToJsonConverter {
...
public JSONObject wayToJson(){
JSONObject obj = new JSONObject();
obj.put(id,way.getId());
...
return obj;
}
...
}

有问题的行是: obj.put(id,way.getId());



有没有办法解决这个问题,然后添加 @SuppressWarnings(unchecked)

解决方案

什么是JSONObject,它是从HashMap继承的?如果是,则可能意味着您应该声明JSONObject实例,如下所示:

  JSONObject< String,Object> obj = new JSONObject< String,Object>(); 

更新:查看JSONObject的定义:

  public class JSONObject extends HashMap 

它扩展了HashMap但是不支持参数类型,如果它的定义是

  public class JSONObject< K,V>扩展HashMap  

然后我们可以写

 的JSONObject<字符串,对象> obj = new JSONObject< String,Object>(); 

,put方法将不再生成警告


I have some data stored in Java elements and I need to return it in a given format - JSONObject. While my implementation works fine, I'm still getting a warning message from eclipse (Version: Juno Service Release 2):

"Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap should be parameterized"

This is my code:

public interface Element {...}

public abstract class AbstractElement implements Element {...}

public final class Way extends AbstractElement {...}

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class WayToJsonConverter{
    ...
    public JSONObject wayToJson(){
        JSONObject obj = new JSONObject();
        obj.put("id",way.getId());
        ...
        return obj;
    }
    ...
}

The problematic line is : obj.put("id",way.getId());

Is there a way to solve this issue other then adding @SuppressWarnings("unchecked")?

解决方案

What is your JSONObject, does it inherit from HashMap? If does, the warn probably means that your should declare the JSONObject instance as follows:

JSONObject<String,Object> obj=new JSONObject<String,Object>();

Updated: Look at the definition of the JSONObject:

public class JSONObject extends HashMap

it extends HashMap but doesn't support parameter type, if its definition is

public class JSONObject<K,V> extends HashMap<K,V>

then we could write

JSONObject<String,Object> obj=new JSONObject<String,Object>();

and the put method will no longer generate the warning

这篇关于Java中的JSON和泛型 - 类型安全警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 22:44