从Java中的JSON数组对象获取字符串值 [英] Getting the string value from a JSON array's object in Java

查看:514
本文介绍了从Java中的JSON数组对象获取字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:其实,我找到了答案。因为我是新的我无法关闭的问题。我能够使用Array.getString(i)返回所需的字符串值。感谢所有帮助。

I actually found the answer. I can't close the question as I am new. I was able to use Array.getString(i) to return the string value needed. Thanks for all the help.

我有JSON是这样的:

I have JSON like this:

{
  "List": [
    "example1",
    "example2",
    "example3",
    "example4"
  ]
}

和我试图获得这些对象的字符串值,而无需使用钥匙。我该怎么办呢?在的getString()为JSONObject的要求的关键,我没有之一。

And I am trying to get the string value of those objects without using a key. How can I do that? The getString() for jsonObject require a key and I don't have one.

推荐答案

我假设你有一个文件: /home/user/file_001.json

I assume that you have a file :/home/user/file_001.json

该文件包含此:`

{"age":34,"name":"myName","messages":["msg 1","msg 2","msg 3"]}

现在让我们写一个程序,读取该文件: /home/user/file_001.json
其内容转换为一个java 的JSONObject

Now let's write a program that reads the file : /home/user/file_001.json and converts its content to a java JSONObject.

package org.xml.json;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;


    public class JsonSimpleRead
    {
        @SuppressWarnings("unchecked")
        public static void main(String[] args)
        {
            JSONParser parser = new JSONParser();
            try
            {
                Object obj = parser.parse(new FileReader("/home/user/file_001.json"));
                JSONObject jsonObject = (JSONObject) obj;
                String name = (String) jsonObject.get("name");
                System.out.println(name);

                long age = (Long) jsonObject.get("age");
                System.out.println(age);

                JSONArray msg = (JSONArray) jsonObject.get("messages");
                Iterator<String> iterator = msg.iterator();
                while (iterator.hasNext())
                {
                    System.out.println(iterator.next());
                }
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (ParseException e)
            {
                e.printStackTrace();
            }
        }
    }

这篇关于从Java中的JSON数组对象获取字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆