Kaninchen Kaninchen - 4 months ago 27
JSON Question

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.

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.

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.

Answer

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.

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];
}
Comments