在JSON文件中使用GSON注释来获取java文件中的值?

时间:2015-06-20 21:48:59

标签: java json

我是JSON的新手。我正在研究在JSON文件中使用GSON注释并将JSON文件中的值转换为Java文件的可能性。我尝试使用" @ serializedname"在JSON文件中,但是不成功。发布的是我的" .JSON"文件和" .java"文件。

JSON文件已获取所有值,我试图将这些值放入.JAVA文件

  {

 "valuess": [
   {
  "color": "red",
  "value": "#f00"
},
{
  "color": "green",
  "value": "#0f0"
},
{
  "color": "blue",
  "value": "#00f"
},
{
  "color": "cyan",
  "value": "#0ff"
},
{
  "color": "magenta",
  "value": "#f0f"
},
{
  "color": "yellow",
  "value": "#ff0"
},
{
  "color": "black",
  "value": "#000"
}
] 
}

这是我拥有的.Java文件

import com.google.gson.annotations.SerializedName;
import java.util.List;
public class file2
{
@SerializedName("valuess")
private List<valuess> vales;

public void setValuess(List<valuess>valuess)
{
   this.vales = valuess;
}
public List<valuess> getVales()
{
    return vales;
}
public String toString()
{
    return "Values are"+vales;
}
}

Values.java

public class Values {


  private String color;
  private  String value;
  Values()
  {

  }
 Values(String Color,String Value)
  {
    this.color=Color;
    this.value = Value;
  }
 public void setColor(String Color)
 {
   this.color = Color;
 }
public void setValue(String Value)
{
    this.value = Value;
}
public String getColor()
{
    return color;
}
public String getValue()
{
    return value;
}
public String toString()
{
    return "Colors[color="+color+"value="+value+"]";
}
}

1 个答案:

答案 0 :(得分:-1)

这应该是你的File2类代码

public class File2
{
    private Valuess[] valuess;

    public Valuess[] getValuess ()
    {
        return valuess;
    }

    public void setValuess (Valuess[] valuess)
    {
        this.valuess = valuess;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [valuess = "+valuess+"]";
    }
}

这应该是你的Valuess类代码

public class Valuess
{
    private String color;

    private String value;

    public String getColor ()
    {
        return color;
    }

    public void setColor (String color)
    {
        this.color = color;
    }

    public String getValue ()
    {
        return value;
    }

    public void setValue (String value)
    {
        this.value = value;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [color = "+color+", value = "+value+"]";
    }
}

现在你可以调用fromJson(String json,Class classOfT)方法将JSON转换为Object:

File2 file2 = new Gson.fromJson(your_json_string_here, File2.class);