Language: Java and Gson
Having parsed a JSON array, how do I:
1) Print all of its contents
2) Iterate over its contents?
For example, here's my code:
String JSInput = "//Json String";
Type listType = new TypeToken<TabClass[]>() {}.getType();
Input_String =GsonObject.fromJson(JSInput, listType);
System.out.println(Input_String.toString());
And the corresponding class description is :
class TabClass{
String Name;
String Parent;
public String getName() {
return Name;
}
public String getParent() {
return Parent;
}
public void setName(String Name) {
this.Name = Name;
}
public void setParent(String Parent) {
this.Parent = Parent;
}
}
The above code only returns a description of the object along with its memory location:
[Lcom.example.projectname.TabClass;@1fbfd6
How do I print the contents of the resultant ob开发者_开发问答ject, or Iterate over it?
It's not necessary to create a TypeToken
just for an array. Gson will deserialize to an array type just fine.
If you have an array, then you don't have to explicitly iterate through its contents just to print. You can use one of the Arrays.toString()
methods.
Here's an example.
// output:
// [{value1=one, value2=1}, {value1=two, value2=2}, {value1=three, value2=3}]
import java.util.Arrays;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args)
{
Gson GsonObject = new Gson();
String JSInput = "[{\"value1\":\"one\",\"value2\":1},{\"value1\":\"two\",\"value2\":2},{\"value1\":\"three\",\"value2\":3}]";
TabClass[] Input_String = GsonObject.fromJson(JSInput, TabClass[].class);
System.out.println(Arrays.toString(Input_String));
}
}
class TabClass
{
private String value1;
private int value2;
@Override
public String toString()
{
return String.format(
"{value1=%s, value2=%d}",
value1, value2);
}
}
Otherwise, if you'd rather explicitly iterate through the components of the array, with Java you have a few choices for how to do so. A simple one is to use the for-each loop construct.
for (TabClass tab : Input_String)
{
System.out.println(tab);
}
(By the way, "Input_String" is not a good name for this array of TabClass
. A more descriptive name might be "tabs".)
精彩评论