This is my JSON data from URL

{"ChannelName":"testChannel","ErrResult":{"ErrCode":0,"Messages":["OK"]},"ModelStateError":{}}

I want to get the value of ChannelName and ErrCode fields

My code is as below

package com.mydomain.java.modules;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

public class JsonTest {

    public static void main(String[] args) {

        // checkurl replace with your JSON URL
        String checkurl = "http://127.0.0.1:8080/livepu/jsonGenerate.php";
        try
        {
            URL connectto = new URL(checkurl);
            HttpURLConnection conn = (HttpURLConnection) connectto.openConnection();
            
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            
            String line;
            
            while ((line = br.readLine()) != null) {
                sb.append(line+"\n");
            }
            
            br.close();
            
            JSONObject jsonObj = new JSONObject(sb.toString());
            System.out.println(jsonObj.getJSONObject("ErrResult").getInt("ErrCode"));
            System.out.println(jsonObj.getString("ChannelName"));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

The result is as below

0
testChannel

 

arrow
arrow

    痞客興 發表在 痞客邦 留言(1) 人氣()