0

I'm fairly new to JSON parsing in Java but when I try and parse this JSON String & find out it's "ID", it repeats the same one twice.

[
  {"id":"{ID1}","time":123},
  {"id":"{ID2}","time":124}
]

This is my Java code:

        // v = json string, c = "id"
        String output = v.replace("[", "").replace("]", "");  
        JSONObject obj = new JSONObject(output);
        ArrayList<String> list = new ArrayList<String>();

        for(int i = 0 ; i < obj.length(); i++){
            System.out.println(obj.getString(c));
            list.add(obj.getString(c));
        }

        return list.get(1);

it returns ID1 twice or more. Please help

11
  • 2
    the json is an array, do not remove the array notation (i.e. the '[' and the ']') Commented Nov 3, 2014 at 17:35
  • so keep that there & keep as is? Commented Nov 3, 2014 at 17:37
  • Where in your loop do you use the loop index i? How would one know which array element to reference? Commented Nov 3, 2014 at 17:40
  • @DwB wont that give me "A JSONObject text must begin with '{'" error? Commented Nov 3, 2014 at 17:41
  • Why do you remove [], when they are what identifies a JSON array? Commented Nov 3, 2014 at 17:41

5 Answers 5

1

Your JSON represents an array - so that's how you should parse it. You can then easily get the id property from each JSONObject within the array. For example:

import org.json.*;

public class Test {
    public static void main(String[] args) throws JSONException {
        String json = 
            "[{\"id\":\"{ID1}\",\"time\":123}, {\"id\":\"{ID2}\",\"time\":124}]";
        JSONArray array = new JSONArray(json);

        for (int i = 0; i < array.length(); i++) {
            JSONObject o = array.getJSONObject(i);
            System.out.println(o.getString("id"));
        }
    }
}

Output:

{ID1}
{ID2}
Sign up to request clarification or add additional context in comments.

Comments

1

I fixed my code by using it as a JSONArray(Thanks @HotLicks)

JSONArray obj = new JSONArray(v);
            ArrayList<String> list = new ArrayList<String>();

            for(int i = 0 ; i < obj.length(); i++){
                Logger.WriteOutput(obj.getJSONObject(i).getString(c), Logger.LogLevel.Info);
            }

Comments

1

Try this :

// This line is useless
// String output = v.replace("[", "").replace("]", "");
JSONArray arr = new JSONArray(output);
ArrayList<String> list = new ArrayList<String>();
for(int i = 0 ; i < arr.length(); i++){
    System.out.println(arr.getJSONObject(i).getString(c));
    list.add(arr.getJSONObject(i).getString(c));
}

Comments

0

First create a java bean for your json (for example here):

public class Item {

    @JsonProperty("id")
    private String  id;
    @JsonProperty("time")
    private Integer time;

    public final String getId() {
        return id;
    }

    public final void setId(String id) {
        this.id = id;
    }

    public final Integer getTime() {
        return time;
    }

    public final void setTime(Integer time) {
        this.time = time;
    }

}

If you are using Jackson Java JSON-processor, you can create a List from JSON-String this way:

    ObjectMapper objectMapper = new ObjectMapper();

    try {
        List<Item> items = objectMapper.readValue(
                    yourJSONString, 
                    objectMapper.getTypeFactory().constructCollectionType(List.class, Item.class));

        for (Item item : items) {
            System.out.println(item.getId());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

5 Comments

There's absolutely no need to create a bean here.
@JonSkeet matter of taste
It looks like considerably more effort to me, for the given task. (In other cases it's very appropriate of course - but compare the amount of code you've provided for an incomplete program with my shorter code which is a self-contained program with the same output.)
@JonSkeet i believe OP wants (perhaps later) more that just getting ID. I tryed to provide an universal OO solution
Given that the OP is returning from the method with just an ID, and they describe their attempt to "find out its ID" I think this is overengineering for the problem described. Of course they may want more later - at which point it would be appropriate. But while there's a simpler solution, I think it's reasonable to present that instead :)
-1

use below code

String v = "[{\"id\":\"ID1\",\"time\":123},{\"id\":\"ID2\",\"time\":124}]";
        String c = "id";
        JSONArray obj = null;
        try {
            obj = new JSONArray(v);

            ArrayList<String> list = new ArrayList<String>();

            for (int i = 0; i < obj.length(); i++) {
                JSONObject j = (JSONObject) obj.get(i);
                System.out.println(j.getString(c));
                list.add(j.getString(c));
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

note that i have slightly corrected the json structure too

before [ {"id":"{ID1}","time":123}, {"id":"{ID2}","time":124} ]

after [ {"id":"ID1","time":123}, {"id":"ID2","time":124} ]

2 Comments

Having "{ID1}" does not make the JSON invalid.
you are right - if he purposefully considered to have "{ID1}" as string. Since he is fairly new to JSON, and his post talks about just returning ID1(not with curly brackets), I have modified the input string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.