我正在使用父类具有SparseArray
private static nested class
的设计。现在,如果我尝试使用GSON
库对父对象进行jsonify,它是否能够对我的父类对象进行jsonify和de-jsonify,因为嵌套类实际上在外部不可见。代码看起来像这样。
class A {
private SparseArray<B> array = new SparseArray<B>();
private A() {}
private static class B {
private B() {}
int example;
}
// static public accessors to access some methods of class A, no object of A outside A
}
我的另一个方面是我不希望任何人在外面创建父类的对象,所以我将默认构造函数保持为私有。我想知道GSON
在我的代码场景中是否会正常运行。
将其转换为JSON
后,SparseList
内的对象似乎转换为null而不是jsonified对象。
答案 0 :(得分:1)
通过使用此测试类找到答案,得出GSON
与每个可见性修饰符无缝地工作,无论是公共还是私有,无论是类,方法,实例变量还是构造函数。我得到的错误是由于SparseArray
的使用,如果它被替换为HashMap
,如下所示就像黄油一样。
package in.mubble.mubbletest;
import java.util.HashMap;
import android.annotation.SuppressLint;
import android.util.Log;
@SuppressLint("UseSparseArrays")
@SuppressWarnings("unused")
public class GSONTest {
private HashMap<Integer, B> myMap;
private String extra;
private GSONTest() {
Log.e("GSONTest", "default constructor GSONTEST was called");
}
public GSONTest(String extra) {
myMap = new HashMap<Integer, B>();
this.extra = extra;
myMap.put(1, new B(7));
Log.e("GSONTest", "parameter constructor GSONTEST was called");
}
private static class B {
int child;
private B() {
Log.e("B", "default constructor B was called");
}
private B(int child) {
Log.e("B", "parameter constructor B was called");
this.child = child;
}
}
public String toString() {
return this.myMap.size() + ": " + this.extra + ", " + this.myMap.get(1).child;
}
}
带有测试代码
GSONTest test = new GSONTest("hahaha");
Gson gson = new Gson();
String json = gson.toJson(test);
Log.e("json", json);
GSONTest result = gson.fromJson(json, GSONTest.class);
Log.e("result", result.toString());
运行时此代码在logcat上生成此输出
parameter constructor B was called
parameter constructor GSONTEST was called
{"extra":"hahaha","myMap":{"1":{"child":7}}}
default constructor GSONTEST was called
default constructor B was called
1: hahaha, 7