Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java-JSONObject只解析1个字符串?_Java_Json - Fatal编程技术网

Java-JSONObject只解析1个字符串?

Java-JSONObject只解析1个字符串?,java,json,Java,Json,我对Java中的JSON解析相当陌生,但是当我尝试解析这个JSON字符串时&发现它是“ID”,它会重复相同的字符串两次 [ {"id":"{ID1}","time":123}, {"id":"{ID2}","time":124} ] 这是我的Java代码: // v = json string, c = "id" String output = v.replace("[", "").replace("]", ""); JSONObje

我对Java中的JSON解析相当陌生,但是当我尝试解析这个JSON字符串时&发现它是“ID”,它会重复相同的字符串两次

[
  {"id":"{ID1}","time":123},
  {"id":"{ID2}","time":124}
]
这是我的Java代码:

        // 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);
//v=json字符串,c=“id”
字符串输出=v.replace(“[”,”).replace(“]”,”);
JSONObject obj=新的JSONObject(输出);
ArrayList=新建ArrayList();
对于(int i=0;i
它返回ID1两次或两次以上。请帮助使用下面的代码

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();
        }
String v=“[{\'id\':\'ID1\',\'time\':123},{\'id\':\'ID2\',\'time\':124}]”;
字符串c=“id”;
JSONArray obj=null;
试一试{
obj=新的JSONArray(v);
ArrayList=新建ArrayList();
对于(int i=0;i
请注意,我也稍微修改了json结构

之前 [ {“id”:“{ID1}”,“time”:123}, {“id”:“{ID2}”,“时间”:124} ]

之后 [ {“id”:“ID1”,“time”:123}, {“id”:“ID2”,“time”:124}
]

首先为json创建一个Javabean(例如):

如果您使用的是Jackson Java JSON处理器,则可以通过以下方式从JSON字符串创建列表:

    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();
    }
ObjectMapper ObjectMapper=new ObjectMapper();
试一试{
列表项=objectMapper.readValue(
yourJSONString,
objectMapper.getTypeFactory().ConstructionCollectionType(List.class,Item.class));
用于(项目:项目){
System.out.println(item.getId());
}
}捕获(IOE异常){
e、 printStackTrace();
}

您的JSON表示一个数组-因此您应该这样解析它。然后,可以从数组中的每个
JSONObject
轻松获取
id
属性。例如:

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"));
        }
    }
}

我通过将代码用作JSONArray修复了代码(谢谢@HotLicks)

JSONArray obj=新的JSONArray(v);
ArrayList=新建ArrayList();
对于(int i=0;i
试试这个:

// 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));
}
//这行没用
//字符串输出=v.replace(“[”,”).replace(“]”,”);
JSONArray arr=新JSONArray(输出);
ArrayList=新建ArrayList();
对于(int i=0;i
json是一个数组,不要删除数组符号(即“[”和“]”),所以保持原样&保持原样?在循环中的何处使用循环索引
i
?如何知道引用哪个数组元素?@DwB不会告诉我“一个JSONObject文本必须以“{”开头的错误?为什么要删除标识JSON数组的
[]
?这里绝对不需要创建bean。@JonSkeet Taste对于我来说,对于给定的任务,它看起来要付出更多的努力。(在其他情况下,这当然是非常合适的——但请将您为一个不完整程序提供的代码量与我的较短代码进行比较,我的较短代码是一个具有相同输出的自包含程序。)@JonSkeet我相信OP需要(可能稍后)不仅仅是获取ID。我试图提供一个通用的OO解决方案,因为OP从方法返回时只有一个ID,他们描述了他们试图“找到它的ID”的尝试我认为这对于所描述的问题来说是过度工程化的。当然,他们以后可能会想要更多——在这一点上,这是合适的。但是,虽然有一个更简单的解决方案,但我认为这样做是合理的:)拥有
“{ID1}”
并不会使JSON无效。你是对的——如果他有意考虑拥有“{ID1}”由于他对JSON相当陌生,并且他的博文谈到只返回ID1(不带花括号),所以我修改了输入字符串。
{ID1}
{ID2}
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);
            }
// 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));
}