使用java中的gson库将过滤后的JSON数据从一个文件复制到另一个文件

时间:2014-09-26 05:36:44

标签: java json parsing gson filtering

我想将JSON字段从一个文件复制到另一个文件但仅在字段满足特定条件后才会复制,例如

{"dataset":
   [
      {"album_id":1,
       "album_type":"Live Performance",
       "artist_name":"John Doe",....
       }
   ] 
}

我只想复制那些用户具有artist_name或任何其他属性的记录,否则跳过元组进行复制。我使用以下代码将过滤后的记录添加到JSONObject" wr"然后我写到我的输出文件。但它没有给我预期的结果

public static void dumpJSONElement(JsonElement element) {
    if (element.isJsonObject()) {
        JsonObject obj = element.getAsJsonObject();
        java.util.Set<java.util.Map.Entry<String,JsonElement>> entries = obj.entrySet();
        java.util.Iterator<java.util.Map.Entry<String,JsonElement>> iter = entries.iterator();
        while (iter.hasNext()) {
            java.util.Map.Entry<String,JsonElement> entry = iter.next();
            if(entry.getKey().equals(filterKey)){
                if(! entry.getValue().toString().replace("\"", "").equals(filterValue)){
                    wr.put(entry.getKey(), entry.getValue());
                }
            }
            else{
                wr.put(entry.getKey(), entry.getValue());
            }
            dumpJSONElement(entry.getValue());
        }

    } else if (element.isJsonArray()) {
        JsonArray array = element.getAsJsonArray();
        java.util.Iterator<JsonElement> iter = array.iterator();
        while (iter.hasNext()) {
            JsonElement entry = iter.next();
            dumpJSONElement(entry); 
        }
    } else if (element.isJsonPrimitive()) {
        JsonPrimitive value = element.getAsJsonPrimitive();

    } else if (element.isJsonNull()) {

    } else {
        System.out.println("Error. Unknown type of element");
    }
}

2 个答案:

答案 0 :(得分:2)

使用代码下面的代码将json字符串转换为通用java类型List<Map<Object, Object>>,使用下面的代码。

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Test {
    public static void main(String... args) {

    String str = "[{'id':1,'name':'yogesh'},{'id':2,'name':'aarush', 'degree': 'MCA'}]";

    Type type = new TypeToken<List<Map<Object, Object>>>() {
    }.getType();

    List<Map<Object, Object>> list = new Gson().fromJson(str, type);

    System.out.println(new Gson().toJson(list));
    filterList(list, "name", "yogesh");
    System.out.println(new Gson().toJson(list));

}

public static void filterList(List<Map<Object, Object>> list, String key, Object value) {
    for (Map<Object, Object> map : list) {
        if (map.containsKey(key)) {
            if (map.get(key).equals(value)) {
                list.remove(map);
            }
        }
    }
}
}

这里我过滤了name = yogesh record。

<强>输出:

[{"id":1.0,"name":"yogesh"},{"id":2.0,"name":"aarush","degree":"MCA"}]
[{"id":2.0,"name":"aarush","degree":"MCA"}]

答案 1 :(得分:0)

我有类似的问题,我用谷歌搜索,阅读了很多关于这一点。总之,最好(最有效)的方式(使用gson)是为你的案例编写一个自定义的TypeAdapter

您可以在下面测试示例代码(它按预期工作):

public static void answer() {

    String jsonAsText = "{\"dataset\":[{\"album_id\":1,\"album_type\":\"Live Performance\",\"artist_name\":\"John Doe\"},{\"album_id\":2,\"album_type\":\"A Dummy Performance\"}]}";

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(List.class, new AlbumInfoListTypeAdapter());

    Gson gson = gsonBuilder.create();

    List<AlbumInfo> dataSet = gson.fromJson(jsonAsText, List.class);

    System.out.println(gson.toJson(dataSet));
}

private static class AlbumInfo {
    int album_id;
    String album_type;
    String artist_name;
}

private static class AlbumInfoListTypeAdapter extends
        TypeAdapter<List<AlbumInfo>> {

    @Override
    public List<AlbumInfo> read(com.google.gson.stream.JsonReader in)
            throws IOException {

        List<AlbumInfo> dataSet = new ArrayList<AlbumInfo>();

        in.beginObject();

        while (in.hasNext()) {
            if ("dataset".equals(in.nextName())) {
                in.beginArray();
                while (in.hasNext()) {
                    in.beginObject();
                    AlbumInfo albumInfo = new AlbumInfo();

                    while (in.hasNext()) {
                        String jsonTag = in.nextName();
                        if ("album_id".equals(jsonTag)) {
                            albumInfo.album_id = in.nextInt();
                        } else if ("album_type".equals(jsonTag)) {
                            albumInfo.album_type = in.nextString();
                        } else if ("artist_name".equals(jsonTag)) {
                            albumInfo.artist_name = in.nextString();
                        }
                    }
                    in.endObject();

                    if (albumInfo.artist_name != null && !"".equals(albumInfo.artist_name.trim())) {
                        dataSet.add(albumInfo);
                    } else {
                        System.out.println("Album info ignored because it has no artist_name value");
                    }
                }
                in.endArray();
            }
        }
        in.endObject();

        return dataSet;
    }

    @Override
    public void write(com.google.gson.stream.JsonWriter out,
            List<AlbumInfo> dataSet) throws IOException {
        out.beginObject();

        out.name("dataset").beginArray();
        for (final AlbumInfo albumInfo : dataSet) {
            out.beginObject();

            out.name("album_id").value(albumInfo.album_id);
            out.name("album_type").value(albumInfo.album_type);
            out.name("artist_name").value(albumInfo.artist_name);

            out.endObject();
        }
        out.endArray();

        out.endObject();
    }
}

您可以修改readwrite方法。 Gson有许多很酷的功能。我强烈建议您阅读this link的样本。

修改

传入的json文字:

{
  "dataset": [
    {
      "album_id": 1,
      "album_type": "Live Performance",
      "artist_name": "John Doe"
    },
    {
      "album_id": 2,
      "album_type": "A Dummy Performance"
    }
  ]
}

System.out.println answer方法的输出:

[
  {
    "artist_name": "John Doe",
    "album_type": "Live Performance",
    "album_id": 1
  }
]