简体   繁体   English

使用List和Hashmap创建Java Json数组对象时输出错误

[英]Output error while creating Java Json array object with List and Hashmap

I want to create an Json array object with List and hashmap, but I have faced some weird problem during the program execution. 我想用List和hashmap创建一个Json数组对象,但是在程序执行过程中遇到了一些奇怪的问题。

This is my code: 这是我的代码:

List<HashMap> list = new ArrayList<>();
HashMap<String, String> hmap = new HashMap<>();
String raw = "<CONTENT><DETAIL><USER>user1</USER><MAIL>abc@test.com</MAIL></DETAIL><DETAIL><USER>user2</USER><MAIL>def@test.com</MAIL></DETAIL></CONTENT>";
String partRas = "";
int index = raw.indexof("<USER>");

while(index >= 0) {
    if(index + 50 < raw.length())
        partRaw = raw.subString(index, index + 50);

    hmap("user", getTagValue(partRaw, "USER"));
    hmap("email", getTagValue(partRaw, "MAIL"));
    list.add(hmap);

    raw = raw.subString(index + 50, raw.length());
    index = raw.indexof("<USER>");
}

System.out.println(new Gson().toJson(list));


public static String getTagValue(String xml, String tagName){
    return xml.split("<"+tagName+">")[1].split("</"+tagName+">")[0];
}

This code looks legit, but when I executed this code, I was expected to have the result like this: 这段代码看起来合法,但是当我执行此代码时,应该得到如下结果:

[{"user":"user1","email":"abc@test.com"},{"user":"user2","email":"def@test.com"}]

but what I got is this: 但是我得到的是:

[{"user":"user2","email":"def@test.com"},{"user":"user2","email":"def@test.com"}]

The only answer to this problem I could figure is " it is PASS BY ADDRESS ", so my first result pushed into List were affected by the second iteration. 我能想到的这个问题的唯一答案是“ 它是PASS BY ADDRESS ”,因此我推入List的第一个结果受到第二次迭代的影响。

The question I want to ask: Does anyone know the way to get the result I wanted? 我想问的问题: 有人知道如何获得我想要的结果吗?

I don't expect the answer to tell me to define multiple HashMaps at the beginning because my raw data might contain more "", which meant it could contain as many of "USER" and "MAIL" data as possible. 我不希望答案告诉我在一开始就定义多个HashMap,因为我的原始数据可能包含更多的“”,这意味着它可能包含尽可能多的“ USER”和“ MAIL”数据。

hmap is being reused in your code, the values are being overwritten, so when you add it to the list you're just adding a new reference to the same thing. hmap在代码中被重用,值被覆盖,因此,将其添加到列表中时,您只是在添加对同一事物的新引用。

List<HashMap> list = new ArrayList<>();
HashMap<String, String> hmap;
String raw = "<CONTENT><DETAIL><USER>user1</USER><MAIL>abc@test.com</MAIL></DETAIL><DETAIL><USER>user2</USER><MAIL>def@test.com</MAIL></DETAIL></CONTENT>";
String partRas = "";
int index = raw.indexof("<USER>");

while(index >= 0) {
    if(index + 50 < raw.length())
        partRaw = raw.subString(index, index + 50);

    /*
     * Create a new, empty HashMap 
     */
    hmap = new HashMap<>();
    hmap("user", getTagValue(partRaw, "USER"));
    hmap("email", getTagValue(partRaw, "MAIL"));
    list.add(hmap);

    raw = raw.subString(index + 50, raw.length());
    index = raw.indexof("<USER>");
}

System.out.println(new Gson().toJson(list));

public static String getTagValue(String xml, String tagName){
    return xml.split("<"+tagName+">")[1].split("</"+tagName+">")[0];
}

You may actually want to check this out (even though error checking is woeful): 您实际上可能想检查一下(即使错误检查很糟糕):

String raw = "<CONTENT><DETAIL><USER>user1</USER><MAIL>abc@test.com</MAIL></DETAIL><DETAIL><USER>user2</USER><MAIL>def@test.com</MAIL></DETAIL></CONTENT>";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;

try {
    dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(new ByteArrayInputStream(raw.getBytes()));
    NodeList nodes = doc.getElementsByTagName("DETAIL");
    for (int idx = 0; idx < nodes.getLength(); idx++) {
        Node node = nodes.item(idx);
        System.out.println("User: "+((Element)node).getElementsByTagName("USER").item(0).getTextContent());
        System.out.println("Mail: "+((Element)node).getElementsByTagName("MAIL").item(0).getTextContent());
    }
} catch (Exception ex) {
    // do stuff
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM