我可以同时管理两者吗?
是的。
为了创建一个与 JSON 结构匹配的 Java 数据结构,我只是从头开始仔细检查 JSON,识别不同的部分,并在 Java 中定义补充。
{ // start object definition
"ESTADO": // add reference of following type
{ // start object definition
"CODIGO": "C", // add reference of type String or an enum
"DESCRIPCION": "Todo bien" // add reference of type String
}, // end object definition
"RESULTADO":
[ // add reference to list or array of the following type
{ // start object definition
"USUARIO": "Silveira García, Francisco", // add String reference
"CENTRO": "I.E.S. Néstor Almendros", // add String reference
"C_CODIGO": "41701183" // add String or number reference
} // end object definition
]
} // end object definition
逐步将 cmets 转换为代码:
// start object definition
class Response
{
}
// start object definition
// add reference of following type
// start object definition
class Response
{
State ESTADO;
}
class State
{
}
// start object definition
// add reference of following type
// start object definition
// add reference of type String or an enum
// add reference of type String
// end object definition
class Response
{
State ESTADO;
}
class State
{
String CODIGO;
String DESCRIPCION;
}
// start object definition
// add reference of following type
// start object definition
// add reference of type String or an enum
// add reference of type String
// end object definition
// add reference to list or array of the following type
// start object definition
class Response
{
State ESTADO;
List<Result> RESULTADO;
}
class Result
{
}
class State
{
String CODIGO;
String DESCRIPCION;
}
// start object definition
// add reference of following type
// start object definition
// add reference of type String or an enum
// add reference of type String
// end object definition
// add reference to list or array of the following type
// start object definition
// add String reference
// add String reference
// add String or number reference
// end object definition
// end object definition
class Response
{
State ESTADO;
List<Result> RESULTADO;
}
class Result
{
String USUARIO;
String CENTRO;
String C_CODIGO;
}
class State
{
String CODIGO;
String DESCRIPCION;
}
实际代码:
import java.io.FileReader;
import java.util.List;
import com.google.gson.Gson;
public class GsonFoo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
Response response = gson.fromJson(new FileReader("input.json"), Response.class);
System.out.println(gson.toJson(response));
}
}
class Response
{
State ESTADO;
List<Result> RESULTADO;
}
class Result
{
String USUARIO;
String CENTRO;
String C_CODIGO;
}
class State
{
String CODIGO;
String DESCRIPCION;
}