使用GSON转换和展平JSON

时间:2018-04-17 11:31:48

标签: json gson jsonreader android

我正在努力将SignalK JSON对象拆分为代表每个值的规范JSON项。

原始JSON如下所示:

{
"mmsi": "urn:mrn:signalk:uuid:5377770-4ee4-4a4b-3230-888037332031",
"name": "Mona",
"navigation": {
    "position": {
        "timestamp": "1991-09-03T03:5:36.000Z",
        "latitude": 51.763691,
        "longitude": 9.501367,
        "altitude": 0.000000,
        "source": "N0183-01"
    },
    "courseOverGroundTrue": {
        "value": 23.000000
    },
    "speedOverGround": {
        "value": 2.010289
    }
},
"environment": {
    "depth": {
        "belowTransducer": {
            "value": 12.700000
        }
    },
    "wind": {
        "angleApparent": {
            "value": 0.174533
        },
        "speedApparent": {
            "value": 0.000000
        }
    }}}

需要转换的JSON看起来像这样,JSON元素代表每个值,项目命名代表值的整个路径。

{
"items": [{
        "columns": {
            "assetId": "urn:mrn:signalk:uuid:5377770-4ee4-4a4b-3230-888037332031",
            "description": "EnvironmentWindSpeedApparent",
            "isStep": false,
            "name": "EnvironmentWindSpeedApparent",
            "timestamps": 1523962903470,
            "type": "numerical",
            "values": 0.0
        },
        "key": "20180417-130143470EnvironmentWindSpeedApparent5377770-4ee4-4a4b-3230-888037332031"
    }, {
        "columns": {
            "assetId": "urn:mrn:signalk:uuid:5377770-4ee4-4a4b-3230-888037332031",
            "description": "EnvironmentWindAngleApparent",
            "isStep": false,
            "name": "EnvironmentWindAngleApparent",
            "timestamps": 1523962903470,
            "type": "numerical",
            "values": 0.174533
        },
        "key": "20180417-130143470EnvironmentWindAngleApparent5377770-4ee4-4a4b-3230-888037332031"
    }, {
        "columns": {
            "assetId": "urn:mrn:signalk:uuid:5377770-4ee4-4a4b-3230-888037332031",
            "description": "EnvironmentDepthBelowTransducer",
            "isStep": false,
            "name": "EnvironmentDepthBelowTransducer",
            "timestamps": 1523962903470,
            "type": "numerical",
            "values": 12.7
        },
        "key": "20180417-130143470EnvironmentDepthBelowTransducer5377770-4ee4-4a4b-3230-888037332031"
    }, {
        "columns": {
            "assetId": "urn:mrn:signalk:uuid:5377770-4ee4-4a4b-3230-888037332031",
            "description": "NavigationPositionLongitude",
            "isStep": false,
            "name": "NavigationPositionLongitude",
            "timestamps": 1523962903470,
            "type": "numerical",
            "values": 9.501367
        },
        "key": "20180417-130143470NavigationPositionLongitude5377770-4ee4-4a4b-3230-888037332031"
    }, {
        "columns": {
            "assetId": "urn:mrn:signalk:uuid:5377770-4ee4-4a4b-3230-888037332031",
            "description": "NavigationPositionLatitude",
            "isStep": false,
            "name": "NavigationPositionLatitude",
            "timestamps": 1523962903470,
            "type": "numerical",
            "values": 51.763691
        },
        "key": "20180417-130143470NavigationPositionLatitude5377770-4ee4-4a4b-3230-888037332031"
    }, {
        "columns": {
            "assetId": "urn:mrn:signalk:uuid:5377770-4ee4-4a4b-3230-888037332031",
            "description": "NavigationCourseOverGroundTrue",
            "isStep": false,
            "name": "NavigationCourseOverGroundTrue",
            "timestamps": 1523962903470,
            "type": "numerical",
            "values": 23.0
        },
        "key": "20180417-130143470NavigationCourseOverGroundTrue5377770-4ee4-4a4b-3230-888037332031"
    }, {
        "columns": {
            "assetId": "urn:mrn:signalk:uuid:5377770-4ee4-4a4b-3230-888037332031",
            "description": "NavigationSpeedOverGround",
            "isStep": false,
            "name": "NavigationSpeedOverGround",
            "timestamps": 1523962903470,
            "type": "numerical",
            "values": 2.010289
        },
        "key": "20180417-130143470NavigationSpeedOverGround5377770-4ee4-4a4b-3230-888037332031"
    }
    ]}

如何以灵活的方式进行此转换,以便更改原始JSON中可用的子节点? 我现在正以简单的方式对其进行转换,但想知道是否可以使用JsonReader,gson或其他迭代原始JSON对象的方式来完成它。

1 个答案:

答案 0 :(得分:0)

我最终定义了表示转换后的json的对象结构,并编写了一个自定义序列化器来进行转换。这可能是更有效的方法,但这种方法似乎工作正常。

public class SignalKDeserializer implements JsonDeserializer<TargetObject> {
//written based on examples from http://www.javacreed.com/gson-deserialiser-example/

final TargetObject targetObject = new TargetObject ();

@Override
public TargetObject deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    final JsonObject jsonObject = json.getAsJsonObject();
    traverse (jsonObject,0,"", mmsi);
    return targetObject;

}

private void traverse (JsonObject jsonObject, Integer level, String parentName, String mmsi) {
    Set<String> keys = jsonObject.keySet();
    Iterator<?> keysIterator = keys.iterator ();
    while( keysIterator.hasNext ()) {
        String key = (String) keysIterator.next ();
        String signalName = parentName+upperCaseFirst (key); //setting signalName to complete path of value
        if (jsonObject.get (key) instanceof JsonObject) {
            traverse ((jsonObject.get (key)).getAsJsonObject (),level+1,upperCaseFirst (signalName),mmsi);
        } else if (jsonObject.get (key) instanceof JsonElement) {
            if (level>0) {
                try {
                    final Double value = jsonObject.get(key).getAsDouble ();
                    calendar = Calendar.getInstance ();
                    Long timeStamp = calendar.getTimeInMillis ();
                    Item targetItem = new Item ();
                    targetItem.columns.setIsStep (false);
                    targetItem.columns.setAssetId (mmsi);
                    targetItem.columns.setTimestamps (calendar.getTimeInMillis ());
                    targetItem.columns.setType ("numerical");
                    targetItem.columns.setDescription (signalName);
                    targetItem.columns.setValues (value);
                    targetItem.columns.setName (signalName);
                    targetItem.setKey (signaldateformat.format (timeStamp) + mmsi);
                    targetObject.items.add (targetItem);
                }
                catch (NumberFormatException n) {
                    // Expected, the value is non numerical and  will not be transformed
                }
            }
        }
    }
}}

我正在使用我的主类中的序列化程序,如下所示:

final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(TargetObject.class, new SignalKDeserializer ());
final Gson gson = gsonBuilder.create();
TargetObject targetObject = gson.fromJson (jsonSignalK,TargetObject.class);
String jsonOutString = gson.toJson (targetObject);

jsonOutString包含我需要的转换后的json。