Java 类org.json.me.JSONArray 实例源码

项目:http4e    文件:JunkUtils.java   
private static String toJSON(String txt, boolean isGWTok, boolean isGWTerr) throws JSONException{

   String res = null;

   if(txt.startsWith("[")){
      JSONArray arr = new JSONArray(txt);
      res = arr.toString(4);         
   } else {
      JSONObject obj = new JSONObject(txt);
      res = obj.toString(4);         
   }
   if (isGWTok) {
      return "//OK" + res;
   } else if (isGWTerr) {
      return "//EX" + res;
   } else {
      return res;
   }
}
项目:pluotsorbet    文件:CommentsLoadOperation.java   
/**
 * Parse a JSON data string into a Vector of CommentThing objects.
 * 
 * @param commentsJson JSON reply to parse into Comments
 * @param startLevel Level of hierarchy to start at (most of the time 0)
 */
protected void parseComments(final String commentsJson, final int startLevel) {
    Vector comments = new Vector();
    JSONObject listingJsonObject;
    try {
        // Recurse through any replies and their replies and ...
        listingJsonObject = new JSONArray(commentsJson).getJSONObject(1);
        recursivelyAddReplies(comments, listingJsonObject, startLevel);
    }
    catch (JSONException e) {
        System.out.println("Error parsing JSON response: " + e.getMessage());
    }

    // Signal the listener when done
    finished = true;
    if (!aborted) {
        listener.commentsReceived(comments);
    }
}
项目:CrapSnap    文件:Friends.java   
private void ShowScore(String Name)
{
    SnapChatApiFx api = new SnapChatApiFx();
    try {
        JSONObject Score = api.GetScore(Name,_Current.getString("username"),_Current.getString("auth_token"));
        JSONObject Friend = Score.getJSONObject(Name);
        JSONArray FriendsArray = Friend.getJSONArray("best_friends");
        String BestString = new String();
        int i = 0;
        for ( i = 0; i < FriendsArray.length();i++)
        {
            BestString = BestString + " " +  FriendsArray.getString(i);
        }
        int score = Friend.getInt("score");
        Dialog.inform(Name + "'s bests friends :" + BestString + ". Score : " + score);
    } catch (JSONException e) {
        Dialog.inform("Unable to get Score.");
        e.printStackTrace();
    }
}
项目:OWGIS    文件:Layer.java   
/**
 * This function adds the layer details but also verifies that the min and max color
 * values don't be -1. If they are then it replaces them by the default color range of
 * the layer.
 *
 * @param {String} layerDetails
 */
public void setLayerDetails(String layerDetailsStr) {

    // In this case we have to update the min and max color with the
    // default color range of the layer. 
    // We add the 'server' and the 'name' into the layer Details
    try {
        JSONObject layDet;
        if (layerDetailsStr.equals("")) {
            this.layerDetails = new JSONObject();
        } else {
            this.layerDetails = new JSONObject(layerDetailsStr);
            if ((this.minColor == -1) && (this.maxColor == -1)) {
                this.minColor = Float.parseFloat((String) (((JSONArray) layerDetails.get("scaleRange")).get(0)));
                this.maxColor = Float.parseFloat((String) (((JSONArray) layerDetails.get("scaleRange")).get(1)));
            }
        }

        layerDetails.accumulate("server", server);
        layerDetails.accumulate("name", name);
        layerDetails.accumulate("srs", this.getProjection());
    } catch (JSONException ex) {
        System.out.println("ERROR: The layerdetails JSON object can't be created on Layer class");
    }
}
项目:pluotsorbet    文件:CommentsLoadOperation.java   
/**
 * Recursively parse the given listingJsonObject for Comments, adding them
 * into the Vector specified. Will call itself until the comment tree is
 * whole (until there are no more child JSON objects to parse).
 * 
 * @param comments Vector of comments
 * @param listingJsonObject JSON object (comment listing) to parse
 * @param level Depth level
 * @throws JSONException In case of a parsing error
 */
protected void recursivelyAddReplies(Vector comments, JSONObject listingJsonObject, int level) throws JSONException {
    JSONArray childrenJsonArray = listingJsonObject
            .getJSONObject("data")
            .getJSONArray("children");

    // Reuse the same objects to avoid unnecessary overhead
    JSONObject thingDataObj;
    CommentThing comment;

    for (int i = 0, len = childrenJsonArray.length(); i < len && !aborted; i++) {

        thingDataObj = childrenJsonArray.getJSONObject(i).getJSONObject("data");

        try {
            // Create a comment item and append it to the list
            comment = CommentThing.fromJson(thingDataObj);
            comment.setLevel(level);
            comments.addElement(comment);
        }
        catch (JSONException e) {
            System.out.println("Could not parse comment JSON: " + e.getMessage());
        }

        // Process any further replies
        JSONObject repliesJsonObject = thingDataObj.optJSONObject("replies");
        if (repliesJsonObject != null) {
            recursivelyAddReplies(comments, repliesJsonObject, level + 1);
        }
    }
}
项目:pluotsorbet    文件:LoginOperation.java   
/**
 * Parse a login JSON response.
 *
 * A successful login response has:
 * - a modhash in the 'data' object
 * - an empty 'errors' array
 *
 * If the response doensn't meet this criteria, the login is interpreted
 * as failed. No further error codes are parsed in the scope of this app.
 *
 * Example of a failed login:
 * {"json": {"errors": [["WRONG_PASSWORD", "invalid password", "passwd"]]}}
 *
 * @param responseJson Login response as JSON
 */
private void parseResponse(String responseJson) {
    String reason = null;
    String modhash = null;
    try {
        JSONObject obj = new JSONObject(responseJson).getJSONObject("json");

        JSONArray errors = obj.getJSONArray("errors");
        JSONObject data = obj.optJSONObject("data");
        if (data != null) {
            modhash = data.optString("modhash");
        }

        // In case of a successful login, invoke the success callback
        if (errors.length() == 0 && modhash != null) {
            finished = true;
            listener.loginSucceeded(username, modhash);
            return;
        }
        // Otherwise try to interpret errors
        else if (errors.length() > 0) {
            String errorCode = errors.getJSONArray(0).getString(0);
            if ("WRONG_PASSWORD".equals(errorCode)) {
                reason = "wrong password";
            } else if ("RATELIMIT".equals(errorCode)) {
                reason = "trying too often";
            }
        }
    }
    catch (Exception e) {
        System.out.println("Error parsing JSON response: " + e.getMessage());
    }

    // If the login conditions were met (or the response couldn't be parsed),
    // invoke the failure callback.
    finished = true;
    listener.loginFailed(reason);
}
项目:pluotsorbet    文件:CommentThing.java   
/**
 * Create a CommentThing from a JSON data String.
 *
 * @param obj JSONObject containing data for the Comment
 * @return A CommentThing object
 * @throws JSONException If the given JSONObject can't be parsed
 */
public static CommentThing fromJson(JSONObject obj) throws JSONException {
    CommentThing thing = new CommentThing();
    thing.setAuthor(obj.optString("author"));
    thing.setBody(HtmlEntityDecoder.decode(obj.optString("body")));

    // Comments have a created date, 'More' items don't
    if (obj.has("created_utc")) {
        try {
            // "1329913184.0" -> "13299131840000"
            String dateStr = obj.getString("created_utc").substring(0, 9) + "0000";
            thing.setCreated(new Date(Long.parseLong(dateStr)));
        }
        catch (Exception e) {
            System.out.println("Couldn't set date: " + e.getMessage());
        }
    }

    thing.setId(obj.optString("id"));        
    thing.setName(obj.optString("name"));
    thing.setScore(obj.optInt("ups"), obj.optInt("downs"));

    // 'Likes' can be true, false or null; map that to 1, -1, and 0
    thing.setVote(
        obj.isNull("likes") ? 0 : obj.getBoolean("likes") ? 1: - 1
    );

    // Set child IDs. These are used for dynamically fetching more replies
    // to a comment.
    JSONArray childrenArray = obj.optJSONArray("children");
    if (childrenArray != null) {
        int len = childrenArray.length();
        String[] childIds = new String[len];
        for (int i = 0; i < len; i++) {
            childIds[i] = childrenArray.getString(i);
        }
        thing.setChildIds(childIds);
    }
    return thing;
}
项目:CrapSnap    文件:FriendSelector.java   
FriendSelector(JSONObject Current, UiApplication app) {
    int direction = Display.DIRECTION_NORTH;
    Ui.getUiEngineInstance().setAcceptableDirections(direction);
    this.setTitle(" CrapSnap - Select Receiver...");
    Bitmap back = EncodedImage.getEncodedImageResource("Back.jpg")
            .getBitmap();
    this.setBackground(BackgroundFactory.createBitmapBackground(back));
    monApp = app;
    Send.setChangeListener(new FieldChangeListener() {
        public void fieldChanged(Field field, int context) {
            exitbol = false;
            if (CheckBox.getChecked() == true) {
                storybol = true;
            }
            quit();
        }
    });

    String[] names;
    try {
        JSONArray friends = Current.getJSONArray("friends");
        names  = new String[friends.length()];
        for (int i = 0; i < friends.length(); i++) {
            JSONObject friend = friends.getJSONObject(i);
            names[i] = friend.getString("name");
        }
        Comparator strComparator = new Comparator() {
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(o2.toString());
            }
        };
        Arrays.sort(names, strComparator);

        for (int i = 0; i < names.length; i++) {
            ListManager.add(new FriendSelectorObject(names[i]));
            ListManager.add(new SeparatorField());
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    this.addMenuItem(AddMenuItem);
    this.addMenuItem(CancelMenuItem);
    BtnManager.add(Send);
    MainManager.add(ListManager);
    HorizontalFieldManager StoryManager = new  HorizontalFieldManager();
    CheckBox.setFont(CheckBox.getFont().derive(Font.BOLD, 9, Ui.UNITS_pt));
    StoryManager.add(new LabelField("  "));
    StoryManager.add(CheckBox);
    MainManager.add(StoryManager);
    MainManager.add(BtnManager);
    this.add(MainManager);
}
项目:CrapSnap    文件:ViewSnap.java   
PopulateThread(JSONArray _snaps) {
    snaps = _snaps;
}
项目:CrapSnap    文件:StoryViewers.java   
StoryViewers(JSONArray MyStory){
    this.setTitle("Who has viewed my story ?");
    Bitmap back = EncodedImage.getEncodedImageResource("Back.jpg").getBitmap();
    this.setBackground(BackgroundFactory.createBitmapBackground(back));
    for (int i = 0; i < MyStory.length(); i++){
        JSONObject Storycore;
        try {
            Storycore = MyStory.getJSONObject(i).getJSONObject("story");
            byte[] img = getImage(
                Storycore.getString("thumbnail_url"),
                Storycore.getString("thumbnail_iv"),
                Storycore.getString("media_key"));
            String Caption = Storycore.getString("caption_text_display");
            if (Caption.equals("")){
                Caption = "Not Named Story.";
            }
            JSONObject StoryExtra = MyStory.getJSONObject(i).getJSONObject("story_extras");
            int viewcount = StoryExtra.getInt("view_count");
            JSONArray StoryNotes = MyStory.getJSONObject(i).getJSONArray("story_notes");
            String ViwerString = "";
            for (int j = 0; j < StoryNotes.length(); j++ ){
                if (ViwerString.equals("")){
                    ViwerString = StoryNotes.getJSONObject(j).getString("viewer");
                } else {
                    ViwerString =  ViwerString + ", " + StoryNotes.getJSONObject(j).getString("viewer") ;
                }
            }
            Bitmap bmp = EncodedImage.createEncodedImage(img, 0, img.length).getBitmap();
            list.add( new Object[] {bmp,Caption, "Viewed " + viewcount + " time(s)",ViwerString});
        } catch (JSONException e) {
            e.printStackTrace();
        }
        list.setCommand(new Command(new CommandHandler(){
            public void execute(ReadOnlyCommandMetadata metadata,
                    Object context) {
                String viewers = (String) list.get(list.getFocusRow())[3];
                Dialog.inform("Viewed by : " + viewers);
            }
        }));
    }
}