[英]How to parse a JSON response when type is also coming in response
I am getting following json response from a web service call. 我正在从Web服务调用中获取json响应。 as you can see, what type of value we will get in response is also coming in type object.
如您所见,类型对象也将传入我们将响应的值的类型。
{"settings":[
{
"name":"name1",
"value":4,
"type":"int"
},
{
"name":"name2",
"value":false,
"type":"boolean"
},
{
"name":"name3",
"type":"array",
"value":[
{
"name":"name3"
}]}]}
Edit: 编辑:
currently i am converting all values to string because we can't add boolean to database. 目前,我正在将所有值都转换为字符串,因为我们无法将布尔值添加到数据库中。
private enum Type{
INT("int"), BOOLEAN("boolean"), ARRAY("array"),UNKNOWN_TYPE("");
private String mType;
Type(String type){
mType = type;
}
public static Type toEnum(String type){
for (Type value: Type.values()){
if(value.mType.equals(type)){
return value;
}
}
return UNKNOWN_TYPE;
}
}
String value = null;
switch (Type.toEnum(type)){
case INT:
value = String.valueOf(setting.getInt("value"));
break;
case BOOLEAN:
value = String.valueOf(setting.getBoolean("value"));
break;
case ARRAY:
parseJsonArray();
break;
}
is this the correct approach? 这是正确的方法吗?
The usual way to deal with data items which could be any of a small known number of types is to use a tagged union . 处理可能是少量已知类型的数据项的通常方法是使用带标记的联合 。 In Java, you'd write one something like this:
在Java中,您将编写如下内容:
// CREATE TABLE dataFromJson (type ENUM('INT', 'BOOLEAN', 'STRING'),
// intval INT, boolval INT, stringval LONGTEXT);
class DataItem {
public enum Type { INT, BOOLEAN, STRING };
public Type m_type;
public int m_int;
public bool m_boolean;
public String m_string;
public PreparedStatement toInsertQuery(Connection conn) {
PreparedStatement ps = conn.prepareStatement("INSERT INTO dataFromJson VALUES (?, ?, ?, ?)");
ps.setString(1, m_type.toString());
if (m_type==INT) ps.setInt(2, m_int); else ps.setObject(2, null);
if (m_type==BOOLEAN) ps.setBoolean(3, m_boolean); else ps.setObject(3, null);
if (m_type==STRING) ps.setString(4, m_string); else ps.setObject(4, null);
return ps;
}
}
Dealing with JSON arrays (and objects) is much trickier; 处理JSON数组(和对象)要复杂得多。 first you'll have to figure out how you want the data to be represented.
首先,您必须弄清楚如何表示数据。 Do you want the whole array as a string?
您是否希望将整个数组作为字符串? do you want the first N elements of the array "exploded" into individual columns?
您是否要将数组的前N个元素“分解”为单独的列? do you want to store a single integer
array_id
, the primary key of a separate and more complicated table ArrayValues
? 是否要存储单个整数
array_id
,这是一个单独的且更复杂的表ArrayValues
的主键? There's all sorts of things you could do here... none of them terribly satisfying on a philosophical level. 您可以在这里做各种各样的事情……在哲学层面上,没有一件事情令人满足。 It depends on what you're going to want to do with the data later.
这取决于您以后要处理的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.