如何在JSONArray之前没有节点时解析Json数据? (机器人)

时间:2014-05-21 05:36:53

标签: android json

[
-{
body: "Deloitte experts believe that Expo 2020 Dubai will be a major “game changer for Dubai” whereby it will create significant changes — whether opportunities or challenges — in most industries and market sectors that could spill over to other countries in the region. “It is clear that Expo 2020 will go beyond a local showcase of commerce, technology and infrastructure, however impressive these things may be,” said Mutasem Dajani, Deloitte UAE regional managing partner. He adds: “Dubai will itself become an agent for future global progress as securing sustainable energy and resources, connecting and moving people, goods and services across markets and exploring the intrinsic spirit of entrepreneurship come together in a location that is uniquely synonymous with achievement in each of these areas.” Humphry Hatton, CEO of Deloitte Corporate Finance Limited (DCFL) regulated by the DIFC, addresses international investments in the region and adds that hosting Expo 2020 in Dubai will “further the attractiveness of Dubai as a base for overseas companies wishing to invest in the Middle East.” Anis Sadek, Dubai managing partner at Deloitte points out that, “It only takes a quick analysis of the impact of an expected additional 20 million international visitors over a six-month period to see that significant investment in hospitality and retail infrastructure will be required.” Rashid Bashir, head of the strategy practice at Deloitte Middle East cautions that “it would be beneficial to develop a dedicated legacy plan to ensure that the event’s potential as a catalyst to transform Dubai’s economy is maximized”. Their views are grouped in the report “Expo 2020: A game changer for Dubai”, and “Countdown to FATCA” available in the spring 2014 issue of the Deloitte Middle East Point of View (ME PoV) publication which also includes the views of other Deloitte partners and industry experts Cynthia Corby, Akbar Ahmad and Jesdev Saggar on the impact of Expo 2022 in the construction, financial services, and infrastructure and capital industries."
created_at: "2014-04-22T08:18:14Z"
date_time: "2014-04-22T08:18:14Z"
department: "Finance"
id: 291
include: true
mediaType: "Domestic Social Media"
priority: "1"
title: "Expo 2020 game will be changer for Dubai"
updated_at: "2014-04-22T08:18:34Z"
user_id: 2
},
-{
body: "Dubai: Dubai’s foreign trade is expected to touch Dh4 trillion by hosting Expo 2020, Mahmoud Al Bastaki, CEO of Dubai Trade, said on day two of the Annual Investment Meeting 2014 in Dubai. “While all business sectors will be growing drastically from now until the hosting of Expo 2020, trade will get the highest leap among all businesses in the UAE,” he said during plenary session at AIM entitle Expo 2020, unlocking new opportunities for potential partnerships in the UAE and the region. In 2013, Dubai trade hit Dh1.392 trillion and was the major contributors to Dubai’s GDP with almost 30 per cent of the total. Ahead of Expo 2020, the government will keep spending on infrastructure, prompting more businesses and investment will come to the UAE. New projects to be developed across all business sectors, and demand on goods will be drastically increase. All these factors will energise the trade market overall, Al Bastaki said. He also added that Expo 2020 will facilitate economic diversification by finding new paths for economic developments. “One of these paths is the development of the physical and social infrastructure, innovation centers and partnership projects.” In line with hosting this big event, the real estate market will witness great developments especially in the area around the Expo site and Dubai World Central. “This alone will boost most of the relevant sectors including wholesale trade, transport and logistics, communications and business services,” The development of other manufacturing industries, cement, construction materials will take part in this boost. Highlighting economic sectors growth and development prior Expo 2020 and how it will go during and after this event, Khalifa Al Zaffin, Executive Chairman of Dubai Aviation City Corporation, in line with Expo 2020 opportunities to capitalise on thriving sector. “In anticipation of the upcoming Expo, Dubai World Central (DWC) has witnessed an increase in land value and development activity which means a potential for attracting new investments,’ Al Zaffin said. “And over the coming years we expect to see a surge in both commercial and residential investments which definitely will be stimulating the small and medium enterprises (SMEs) as well as services sector,” he added. During Expo 2020, Al Zaffin portray how DWC will be a unique business and residential community district during expo. “DWC will include all facilities for businesses, residents and visitors. There will be districts for logistic, business, commercial, residential, exhibitions, hospitality, humanitarian and entertainment.” All these will be developed by attracted a lot of local and foreign investors, and will be resulting in natural growth of Gross Domestic Production (GDP) during and after Expo 2020, he added. Infrastructure UAE and Dubai is going to invest heavily on infrastructure ahead of Expo 2020, said Khalid Al Malek, CEO Group of Dubai Properties Group, during the plenary session. He also expected this to enhance growth in other relative sectors, including real estate and construction. According to the latest statistic last year, Al Malek said, construction and infrastructure projects announced and underway in the Gulf Cooperation Council (GCC) countries accounts for $1.9 trillion while UAE’s shares accounts for 49 per cent of the overall projects. “UAE continues to remain the largest projects market, with around $940 billion project that have been under execution,” he added. Projects in the UAE are dominated by infrastructure and construction, as several large projects that were earlier deferred or delayed have been revived, he said. Sizeable investment in utilities is taking place as well, given the ambitious long-term growth plans, according to him. Al Malek described the overall investment climate as a conducive with well established infrastructure and connectivity with the rest of the world. This is one of the advantage that Dubai enjoys to attract investments. Adding to this, he remarked that significant availability of low cost natural resources, consistent GDP growth and generation of surplus, high positioning in transparency and competitiveness index, re-export hub, developed free zones and strategic location are Dubai’s economic strength, Al Malek said."
created_at: "2014-04-15T10:19:07Z"
date_time: "2014-04-15T10:19:07Z"
department: "Finance"
id: 247
include: true
mediaType: "International Established"
priority: "1"
title: "Dubai Expo 2020 to produce Dh4 trillion foreign trade"
updated_at: "2014-04-15T10:19:16Z"
user_id: 2
}]

以上是我的完整 json数据。我通过编写下面的代码成功地将json数据成功地写入了我的logcat。

HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Accept", "application/json");
try {
    HttpResponse httpResponse = httpClient.execute(httpGet);
    StatusLine statusLine = httpResponse.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode != 200) {
        Toast.makeText(MainActivity.this, "error" + statusCode,
        Toast.LENGTH_SHORT).show();
        return null;
    }
    HttpEntity httpEntity = httpResponse.getEntity();
    InputStream inputStream = httpEntity.getContent();
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(inputStream));
    StringBuilder stringBuilder = new StringBuilder();
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line);
    }
String jsonData = stringBuilder.toString();
//To display json data in LOGCAT
Log.d("Latest 20 feeds", jsonData);

我的问题是我如何解析数据并在logcat中显示,例如:所有" title"," body"等

5 个答案:

答案 0 :(得分:2)

首先,您有无效的JSON数据。我不知道你是如何检查并发现它有效但我发现了很多errors你可以通过粘贴它来检查JSON Validate 我删除了您的一些STRING数据以使其在空间中很好地移除并移除了errors,因此它的外观如下所示

[
{
"body": "Deloitte experts believe that Expo 2020 Dubai will and infrastructure and capital industries.",
"created_at": "2014-04-22T08:18:14Z",
"date_time": "2014-04-22T08:18:14Z",
"department": "Finance",
"id": 291,
"include": true,
"mediaType": "Domestic Social Media",
"priority": "1",
"title": "Expo 2020 game will be changer for Dubai",
"updated_at": "2014-04-22T08:18:34Z",
"user_id": 2
},
{
"body": "Dubai: Dubai’s foreign trade is expected to, Al Malek said.",
"created_at": "2014-04-15T10:19:07Z",
"date_time": "2014-04-15T10:19:07Z",
"department": "Finance",
"id": 247,
"include": true,
"mediaType": "International Established",
"priority": "1",
"title": "Dubai Expo 2020 to produce Dh4 trillion foreign trade",
"updated_at": "2014-04-15T10:19:16Z",
"user_id": 2
}
]

现在它的格式有效,所以你现在需要做的就是......

JSONAarray array = new JSONArray(JsonString);
for(int i=0; i<array.length(); i++){
    JSONObject object = array.getJSONObject(i);
    String title = object.getString("title");
    String body = object.getString("body");
    System.out.println("Titlte: " + title);
    System.out.println("Body: " + body);
}

答案 1 :(得分:2)

以这种方式动态迭代JSON

创建这些方法

1)

public void parseJson(JSONArray data) {
        try {
            JSONObject obj = new JSONObject();
            obj.put("data", data);

            parseJson(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2)

    private void parseJson(JSONObject data) {

        if (data != null) {
            Iterator<String> it = data.keys();
            while (it.hasNext()) {
                String key = it.next();

                try {
                    if (data.get(key) instanceof JSONArray) {
                        JSONArray arry = data.getJSONArray(key);
                        int size = arry.length();
                        for (int i = 0; i < size; i++) {
                            parseJson(arry.getJSONObject(i));
                        }
                    } else if (data.get(key) instanceof JSONObject) {
                        parseJson(data.getJSONObject(key));
                    } else {
                        System.out.println(key + " : " + data.getString(key));
                    }
                } catch (Throwable e) {
                    try {
                        System.out.println(key + " : " + data.getString(key));
                    } catch (Exception ee) {
                    }
                    e.printStackTrace();

                }
            }
        }
    }

如何使用?

String jsonData = stringBuilder.toString();
        try {
            parseJson(new JSONArray(jsonData));
        } catch (Exception e) {
        }

答案 2 :(得分:0)

我会确保你得到的json字符串是有效的。当它是有效的JSON时,通过使用随jsonData字符串提供的JSONArray构造函数,您将获得json对象的JSONArray。这是一个完整的例子:

jsonData = "{" + jsonData + "}";
JSONArray json = new JSONArray(jsonData);

我希望您使用的是this JSON库。

从我的调查来看,这是无效的(缺少半列等)。您可以使用this工具验证您的json。

这是一个有效的json字符串:

[
    {
        "body": "Deloitte experts believe that Expo 2020 Dubai will be a major “game changer for Dubai” whereby it will create significant changes — whether opportunities or challenges — in most industries and market sectors that could spill over to other countries in the region. “It is clear that Expo 2020 will go beyond a local showcase of commerce, technology and infrastructure, however impressive these things may be,” said Mutasem Dajani, Deloitte UAE regional managing partner. He adds: “Dubai will itself become an agent for future global progress as securing sustainable energy and resources, connecting and moving people, goods and services across markets and exploring the intrinsic spirit of entrepreneurship come together in a location that is uniquely synonymous with achievement in each of these areas.” Humphry Hatton, CEO of Deloitte Corporate Finance Limited (DCFL) regulated by the DIFC, addresses international investments in the region and adds that hosting Expo 2020 in Dubai will “further the attractiveness of Dubai as a base for overseas companies wishing to invest in the Middle East.” Anis Sadek, Dubai managing partner at Deloitte points out that, “It only takes a quick analysis of the impact of an expected additional 20 million international visitors over a six-month period to see that significant investment in hospitality and retail infrastructure will be required.” Rashid Bashir, head of the strategy practice at Deloitte Middle East cautions that “it would be beneficial to develop a dedicated legacy plan to ensure that the event’s potential as a catalyst to transform Dubai’s economy is maximized”. Their views are grouped in the report “Expo 2020: A game changer for Dubai”, and “Countdown to FATCA” available in the spring 2014 issue of the Deloitte Middle East Point of View (ME PoV) publication which also includes the views of other Deloitte partners and industry experts Cynthia Corby, Akbar Ahmad and Jesdev Saggar on the impact of Expo 2022 in the construction, financial services, and infrastructure and capital industries.",
        "created_at": "2014-04-22T08:18:14Z",
        "date_time": "2014-04-22T08:18:14Z",
        "department": "Finance",
        "id": 291,
        "include": true,
        "mediaType": "Domestic Social Media",
        "priority": 1,
        "title": "Expo 2020 game will be changer for Dubai",
        "updated_at": "2014-04-22T08:18:34Z",
        "user_id": 2
    },
    {
        "body": "Dubai: Dubai’s foreign trade is expected to touch Dh4 trillion by hosting Expo 2020, Mahmoud Al Bastaki, CEO of Dubai Trade, said on day two of the Annual Investment Meeting 2014 in Dubai. “While all business sectors will be growing drastically from now until the hosting of Expo 2020, trade will get the highest leap among all businesses in the UAE,” he said during plenary session at AIM entitle Expo 2020, unlocking new opportunities for potential partnerships in the UAE and the region. In 2013, Dubai trade hit Dh1.392 trillion and was the major contributors to Dubai’s GDP with almost 30 per cent of the total. Ahead of Expo 2020, the government will keep spending on infrastructure, prompting more businesses and investment will come to the UAE. New projects to be developed across all business sectors, and demand on goods will be drastically increase. All these factors will energise the trade market overall, Al Bastaki said. He also added that Expo 2020 will facilitate economic diversification by finding new paths for economic developments. “One of these paths is the development of the physical and social infrastructure, innovation centers and partnership projects.” In line with hosting this big event, the real estate market will witness great developments especially in the area around the Expo site and Dubai World Central. “This alone will boost most of the relevant sectors including wholesale trade, transport and logistics, communications and business services,” The development of other manufacturing industries, cement, construction materials will take part in this boost. Highlighting economic sectors growth and development prior Expo 2020 and how it will go during and after this event, Khalifa Al Zaffin, Executive Chairman of Dubai Aviation City Corporation, in line with Expo 2020 opportunities to capitalise on thriving sector. “In anticipation of the upcoming Expo, Dubai World Central (DWC) has witnessed an increase in land value and development activity which means a potential for attracting new investments,’ Al Zaffin said. “And over the coming years we expect to see a surge in both commercial and residential investments which definitely will be stimulating the small and medium enterprises (SMEs) as well as services sector,” he added. During Expo 2020, Al Zaffin portray how DWC will be a unique business and residential community district during expo. “DWC will include all facilities for businesses, residents and visitors. There will be districts for logistic, business, commercial, residential, exhibitions, hospitality, humanitarian and entertainment.” All these will be developed by attracted a lot of local and foreign investors, and will be resulting in natural growth of Gross Domestic Production (GDP) during and after Expo 2020, he added. Infrastructure UAE and Dubai is going to invest heavily on infrastructure ahead of Expo 2020, said Khalid Al Malek, CEO Group of Dubai Properties Group, during the plenary session. He also expected this to enhance growth in other relative sectors, including real estate and construction. According to the latest statistic last year, Al Malek said, construction and infrastructure projects announced and underway in the Gulf Cooperation Council (GCC) countries accounts for $1.9 trillion while UAE’s shares accounts for 49 per cent of the overall projects. “UAE continues to remain the largest projects market, with around $940 billion project that have been under execution,” he added. Projects in the UAE are dominated by infrastructure and construction, as several large projects that were earlier deferred or delayed have been revived, he said. Sizeable investment in utilities is taking place as well, given the ambitious long-term growth plans, according to him. Al Malek described the overall investment climate as a conducive with well established infrastructure and connectivity with the rest of the world. This is one of the advantage that Dubai enjoys to attract investments. Adding to this, he remarked that significant availability of low cost natural resources, consistent GDP growth and generation of surplus, high positioning in transparency and competitiveness index, re-export hub, developed free zones and strategic location are Dubai’s economic strength, Al Malek said.",
        "created_at": "2014-04-15T10: 19: 07Z",
        "date_time": "2014-04-15T10: 19: 07Z",
        "department": "Finance",
        "id": 247,
        "include": true,
        "mediaType": "InternationalEstablished",
        "priority": 1,
        "title": "DubaiExpo2020toproduceDh4trillionforeigntrade",
        "updated_at": "2014-04-15T10: 19: 16Z",
        "user_id": 2
    }
]

答案 3 :(得分:0)

在您的示例JSONArray中。因此,您可以将其解析为对象数组。简单的方法是使用Gson:

String jsonData = stringBuilder.toString();
Gson gson = new Gson();
MyDataObject [] data = gson.fromJson(jsonData, MyDataObject[].class);

答案 4 :(得分:0)

使用Google GSON lib进行自动解析(只需下载最新版本的GSON jar文件并将其放入libs文件夹中的项目中):

1)创建描述数据模型的类

    public class SomeObjectClass {
        @SerializedName("body")
        private String mBody;

        @SerializedName("created_at")
        private String mCreatedAt;

        @SerializedName("date_time")
        private String mDateTime;

        @SerializedName("department")
        private String mDepartment;

        @SerializedName("id")
        private long mId;

        @SerializedName("include")
        private boolean mInclude;

        // another fields here

        // some getters if you need it
    }

2)创建将json字符串解析为对象列表的方法

    public List<SomeObjectClass> parseJson(String jsonArray) {
        Type listType = new TypeToken<ArrayList<SomeObjectClass>>() {}.getType();
        List<SomeObjectClass> yourClassList = new Gson().fromJson(jsonArray, listType);
        return yourClassList;
    }

3)解析你的json

List<SomeObjectClass> objects = parseJson(jsonData);

4)迭代它并记录