字符串无法转换为JSON数组

时间:2013-03-09 00:47:57

标签: java php android json parsing

每次尝试执行代码时都会出现以下错误:

03-09 00:41:23.022: E/JustDealsUtils(1163): Error parsing to json on getJarrayFromString(); org.json.JSONException: Value Database of type java.lang.String cannot be converted to JSONArray
03-09 00:41:23.022: E/ActivityTab(1163): Error at fillPromotionList(): java.lang.NullPointerException

Java剪辑了fillPromotionList()

public void onTaskCompleted(String result) {
  try {
    // converting the response into json array
    if(result != "") {
      jarray = utils.getJarrayFromString(result);

      // total number of rows for a query
      int mysqlSize = (jarray.getJSONObject(0)
        .getInt("numRows"));

      Log.i(DEBUG, "From " + from + " to " + mysqlSize);

      if(from <= mysqlSize) {
        int rows;
        if(jarray.length() > 0) {
          Log.i(DEBUG, "From " + from + " to " + Math.floor(mysqlSize / nr) * nr);
          if(from + 5 <= Math.floor(mysqlSize / nr) * nr) {
            rows = jarray.length();
          } else {
            rows = mysqlSize % nr + 1;
            Utils.IS_ENDED_PROMO_LIST = true;
          }
          ArrayList < String > list = new ArrayList < String > ();
          for(int i = 1; i < rows; i++) {
            JSONObject row = jarray.getJSONObject(i);
            soid.add(row.getInt("bid"));
            soTitle.add(row.getString("bTitle"));
            soCode.add(row.getString("bCode"));
            soPrice.add(row.getString("bPrice") + "£");
            soDescription.add(row.getString("bDescription"));
            soModule.add(row.getString("bModule"));
            soImage.add(Utils.PATH + row.getString("bImage"));
            soDiscount.add(row.getInt("bSpecialDiscount"));
            list.add(row.getString("bImage"));
            if(!db.hasIDBooks(row.getInt("bid"))) db.createRowOnBooks(row.getInt("bid"), row.getString("bTitle"), row.getString("bCode"), row.getString("bPrice"), row.getString("bDescription"), row.getString("bModule"), Utils.PATH + row.getString("bImage"), row.getString("bSpecialOffer"), row.getInt("bSpecialDiscount"), row.getString("bDateAdded"));
          }
          new DownloadImages(list, soAdapter)
            .execute();
        }
      }
      postParameters.removeAll(postParameters);
    } else {
      Utils.IS_ENDED_PROMO_LIST = true;
      if(rlLoading.isShown()) {
        rlLoading.startAnimation(fadeOut());
        rlLoading.setVisibility(View.INVISIBLE);
      }
    }
  } catch(Exception e) {
    Log.e(DEBUG, "Error at fillPromotionList(): " + e.toString());
  }
}
});

我为另一个列表函数编写了相同的代码,它工作正常。我无法纠正这个问题。

此外,它还指向空指针异常??

以下是此代码的PHP API:

<?php
    include("MysqlConnection.php");
    $from = $_POST["from"];
    $nr = $_POST["nr"];
    // those variables are for search
    $title = $_POST["title"];
    $code = $_POST["code"];
    $price = $_POST["price"];
    $module = $_POST["module"];
    $order = $_POST["order"];
    $by = $_POST["by"];


    $sql = "SET CHARACTER SET utf8";
    $db->query($sql);

    if(isset($from) && isset($nr)){
        // we need to know how many rows are in total for this query
        $sql = "SELECT * FROM `books` WHERE `bSpecialOffer='true' AND `bCode` LIKE '%$code%' AND `bTitle` LIKE '%$title%' AND `bModule` LIKE '%$module%'";
        $query = $db->query($sql);

        $rows = array();
        $rows[] = array("numRows"=>$db->numRows($query));

        // if those 2 var are set then we order the query after them
        if(isset($order) && isset($by)){
            $sql .= " ORDER BY `$order` $by LIMIT $from, $nr";
        }else{
            $sql .= "LIMIT $from, $nr";
        }

        $query = $db->query($sql);

        if($db->numRows($query)!=0){
            while($row = mysql_fetch_assoc($query)) {
                $rows[] =  $row;
            }
            print_r(json_encode($rows));
        }
    }

    $db->closeConnection();
?>

实际上错误也提到了DATABASE VALUE。这是否意味着错误在于PHP API?

最后,这是utils.java中的JSON数组部分:

 public JSONArray getJarrayFromString(String result) {
   // Parsing string to JSON Array
   try {
     jarray = new JSONArray(result);
   } catch(JSONException e) {
     Log.e(DEBUG, "Error parsing to json on getJarrayFromString(); " + e.toString());
   }

   return jarray;
 }

您的建议和意见将受到高度赞赏。非常感谢。

来自SQL数据库的BOOKS表的片段。

CREATE TABLE `books` (
  `bid` int(11) NOT NULL auto_increment,
  `bCode` varchar(50) NOT NULL,
  `bTitle` varchar(100) NOT NULL,
  `bPrice` int(50) NOT NULL,
  `bDescription` longtext NOT NULL,
  `bModule` varchar(50) NOT NULL,
  `bImage` varchar(80) NOT NULL,
  `bDateAdded` date NOT NULL,
  `bSpecialOffer` varchar(5) NOT NULL,
  `bSpecialDiscount` int(3) NOT NULL,
  PRIMARY KEY  (`bid`),
  UNIQUE KEY `bTitle` (`bTitle`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=49 ;

--
-- Dumping data for table `books`
--

INSERT INTO `books` VALUES(1, "MDAI001", "Apocalyptic AI", 50, "Author: Robert M.Geraci\r\n\r\nEdition: 5th Edition \r\n\r\nTopics: Intelligence Agents,Solving problems by seraching, Beyond classical search, Algorithms and Adversarial search, logical agents", "MDAI72", "image26.jpg", "2013-01-12", "true", 30);
INSERT INTO `books` VALUES(19, 'MDAI002', 'Programming Game AI by Example', 15, 'Author: Mat Buckland\r\n\r\nEdition: 2nd Edition \r\n\r\nTopics: Learning from examples, Knowledge in learning, Reinforcement learning, Learning probabalistic model, Non parametric models', 'MDAI72', 'image27.jpg', '2013-01-25', 'false', 0);
INSERT INTO `books` VALUES(20, 'MDAI003 ', 'Artificial Inteligence', 26, 'Author: George F Luger\r\n\r\nEdition: 1st Edition \r\n\r\nTopics: Artificial neural networks, Language models, Speech recognition, Syntactic analysis, Image formation, Reconstructing the 3D world, Machine translation ', 'MDAI72', 'image28.jpg', '2012-05-18', 'false', 0);
INSERT INTO `books` VALUES(21, 'MDAI004 ', 'Artificial Intelligence Programming', 10, 'Author: Peter Narvig\r\n\r\nEdition: 3rd Edition \r\n\r\nTopics: Learning from examples, Knowledge in learning, Reinforcement learning, Learning probabalistic model, Non parametric models\r\n', 'MDAI72', 'image29.jpg', '2012-03-17', 'false', 0);
INSERT INTO `books` VALUES(22, 'MDAI005', 'Artificial Intelligence: A Systems Approach', 35, 'Author: Dan Jones\r\n\r\nEdition: 2nd Edition \r\n\r\nTopics: Robotic perception, Robotic software architectures, Strong AI vs Weak AI,  The ethics and risks of developing AI, Can machines really think? \r\n', 'MDAI72', 'image30.jpg', '2012-01-20', 'false', 0);
INSERT INTO `books` VALUES(24, 'MDSC001 ', 'Distributed and Cloud Computing', 30, 'Author: Kay Hwang\r\n\r\nEdition: 3rd Edition \r\n\r\nTopics: Modern distributed models, Peer-to-peer computing, Open source and commercial vendors', 'MDSC48', 'image21.jpg', '2012-02-16', 'false', 0);
INSERT INTO `books` VALUES(25, 'MDSC002', 'Computing in the Social Sciences and Humanities', 12, 'Author: Orville Vernon Burton \r\n\r\nEdition: 5nd Edition \r\n\r\nTopics:A lively, hands-on introduction for teachers and scholars in the humanities and social sciences, this book-and-CD package will inspire even the faint-hearted to take the technological bull by the horns and make efficient, informed use of computer and Internet resources. New technology is changing the very nature of research and teaching in the social sciences and humanities.', 'MDSC48', 'image22.jpg', '2012-03-17', 'false', 0);
INSERT INTO `books` VALUES(26, 'MDSC003', 'Identity in the age of Cloud Computing ', 30, 'Author: J.D.Lasica\r\n\r\nEdition: 1st Edition \r\n\r\nTopics: The Mobile Generation: Global Transformations at the Cellular Level, Civic Engagement on the Move: How Mobile Media Can Serve the Public Good, Identity in the Age of Cloud Computing: The next-generation Internet’s impact on business, governance and social interaction', 'MDSC48', 'image23.jpg', '2012-10-10', 'false', 0);
INSERT INTO `books` VALUES(27, 'MDSC004', 'To the Cloud- Powering an Enterprise', 23, 'Author: Pankaj Arora\r\n\r\nEdition: 4th Edition \r\n\r\nTopics: Understand the Cloud\r\nUnderstand the Value Proposition\r\nChart the Cloud Landscape', 'MDSC48', 'image24.jpg', '2012-01-12', 'true', 20);
INSERT INTO `books` VALUES(28, 'MDSC005 ', 'Building Virtual Communities', 35, 'Author: K. Ann Renninger\r\n\r\nEdition: 1st Edition \r\n\r\nTopics: Building Virtual Communities examines how learning and cognitive change are fostered by online communities. Contributors to this volume explore this question by drawing on their different theoretical backgrounds, methodologies, and personal experience with virtual communities. Each chapter discusses the different meanings of the terms community, learning, and change', 'MDSC48', 'image25.jpg', '2012-09-23', 'false', 0);
INSERT INTO `books` VALUES(29, 'MDSE001', 'Software Engineering: Principles and Practice', 12, 'Author: Hans Van Vliet \r\n\r\nEdition: 3rd Edition \r\n\r\nTopics: \r\nIntroduction to Software Engineering Management, The Software Life Cycle Revisited, Configuration Management, People Management and Team Organization, On Managing Software Quality, Cost Estimation, Project Planning and Control \r\n', 'MDSE80', 'image16.jpg', '2012-05-17', 'false', 0);
INSERT INTO `books` VALUES(30, 'MDSE002', 'Software Engineering: A Practioners Approach', 25, 'Author: Roger.S.Pressman\r\n\r\nEdition: 7th Edition \r\n\r\nTopics: \r\nThe seventh edition is considerably more than a simple update. The book has been revised and restructured to improve pedagogical flow and emphasize new and important software engineering processes and practices. In addition, a revised and updated “support system,” illustrated below, provides a comprehensive set of student, instructor, and professional resources to complement the content of the book.\r\n', 'MDSE80', 'image17.jpg', '2012-07-19', 'false', 0);
INSERT INTO `books` VALUES(31, 'MDSE003', 'Software Engineering for Students: A programming approach', 25, 'Author: Douglas Bell\r\n\r\nEdition: 4th Edition \r\n\r\nTopics: Software Engineering for Students presents a range of current techniques and tools for people who have experienced the pleasures of writing programs and who want to see how things change in the scale up to large programs and software systems.\r\n\r\n', 'MDSE80', 'image18.jpg', '2012-04-13', 'false', 0);
INSERT INTO `books` VALUES(32, 'MDSE004', 'Object Oriented Software', 32, 'Author: Michael Smith \r\n\r\nEdition: 2nd Edition \r\n\r\nTopics: The book covers ANSI C++ and is illustrated with numerous programming examples. The first few chapters introduce computer programming for those who have no previous programming knowledge. The book avoids the early use of low level constructs such as pointers so that the key object-oriented concepts can be fully introduced', 'MDSE80', 'image19.jpg', '2012-04-17', 'false', 0);
INSERT INTO `books` VALUES(33, 'MDPG001', 'iPhone Programming', 14, 'Author: Alasdair Allan\r\n\r\nEdition: 1st Edition \r\n\r\nTopics: The book guides you through developing your first application for the iPhone, from opening Xcode for the first time, to submitting your application to the App Store. You''ll learn about Objective-C and the core frameworks needed to develop for the iPhone by writing applications that use them, giving you a basic framework for building your own applications independently.\r\n', 'MDPG70', 'image6.jpg', '2012-07-19', 'false', 0);
INSERT INTO `books` VALUES(34, 'MDPG002', 'Java: Introduction to Problem Solving and Programming', 29, 'Author: Walter Savitch\r\n\r\nEdition: 1st Edition \r\n\r\nTopics: For introductory Computer Science courses using Java (CS1with Java), and other introductory programming courses in departments of Computer Science, Computer Engineering, Computer Information Systems, Management Information Systems, Information Technology, and Business.', 'MDPG70', 'image7.jpg', '2012-07-12', 'false', 0);
INSERT INTO `books` VALUES(35, 'MDSE005', 'Object-Oriented and Classical Software Engineering', 26, 'Author: Stephen R.Schach\r\n\r\nEdition: 8th Edition \r\n\r\nTopics: Building on seven strong editions, the eighth edition maintains the organization and approach for which "Object-Oriented and Classical Software Engineering" is known while making significant improvements and additions to content as well as problems and projects.\r\n', 'MDSE80', 'image20.jpg', '2012-10-17', 'false', 0);
INSERT INTO `books` VALUES(36, 'MDPG003', 'Web Services with Perl', 18, 'Author: Randy J. Ray\r\n\r\nEdition: 2nd Edition \r\n\r\nTopics: Given Perl''s natural fit for web applications development, it''s no surprise that Perl is also a natural choice for web services development. It''s the most popular web programming language, with strong implementations of both SOAP and XML-RPC, the leading ways to distribute applications using web services. But books on web services focus on writing these applications in Java or Visual Basic, leaving Perl programmers with few resources to get them started. Programming Web Services with Perl changes that, bringing Perl users all the information they need to create web services using their favorite language.', 'MDPG70', 'image8.jpg', '2012-07-20', 'false', 0);
INSERT INTO `books` VALUES(37, 'MDPG004', 'Effective TCP/IP Programming: 44 Tips to Improve Your Network Programs', 34, 'Author: Jon C. Snader\r\n\r\nEdition: 4th Edition \r\n\r\nTopics: An excellent next-step for students who have read Stevens'' TCP/IP Illustrated series, this book is designed to boost programmers to a higher level of competence by focusing on the protocol suite''s more subtle features and techniques. In forty-four concise, self-contained lessons, this book offers experience-based tips, practices, and rules of thumb for learning high-performance TCP/IP programming techniques. Moreover, it shows you how to avoid many of TCP/IP''s most common trouble spots.', 'MDPG70', 'image9.jpg', '2012-02-25', 'false', 0);
INSERT INTO `books` VALUES(38, 'MDPG005', 'Pro Java Programming', 34, 'Author: Brett Spell\r\n\r\nEdition: 2nd Edition \r\n\r\nTopics: Pro Java Programming, Second Edition covers the J2SE 5.0 platform and the core Java development kit. It takes advantage of the finer points of the core and standard edition of Java 2. You''ll discover the particulars of working with the Java language and APIs to develop applications in many different contexts.', 'MDPG70', 'image10.jpg', '2012-10-20', 'false', 0);
INSERT INTO `books` VALUES(39, 'MDEC001', 'E-commerce: Business. Technology. Society', 26, 'Author: Kenneth C. Laudon\r\n\r\nEdition: 2nd Edition \r\n\r\nTopics: Electronic commerce: Business. Technology. Society. provides an overview of the current and next generations of e-commerce. The book emphasizes the three major driving forces behind e-commerce: business development, technology change, and social controversies.', 'MDEC20', 'image11.jpg', '2012-08-18', 'false', 0);
INSERT INTO `books` VALUES(40, 'MDEC002 ', 'E-commerce Technology Foundations', 17, 'Author: Davis and Benamati\r\n\r\nEdition: 3rd Edition \r\n\r\nTopics: In E-Commerce Basics, the authors introduce the basic technological infastructure and business issues to understand when analyzing the feasibility of e-commerce initiatives\r\n', 'MDEC20', 'image12.jpg', '2012-10-16', 'false', 0);
INSERT INTO `books` VALUES(41, 'MDEC003', 'E-business and E-commerce Management', 21, 'Author: Dave Chaffey\r\n\r\nEdition: 3rd Edition \r\n\r\nTopics:A comprehensive assessment of the management issues faced in implementing e-business solutions, this book is suitable for students or practitioners of e-business, e-commerce or e-marketing at any level. Each chapter contains management issues, activities and answers, case studies, questions for debate, self-assessment exercises, discussion, essay and exam questions, further reading, web links and more.\r\n', 'MDEC20', 'image13.jpg', '2012-05-13', 'false', 0);
INSERT INTO `books` VALUES(42, 'MDEC004', 'The Complete E-Commerce Book', 22, 'Author: Janice Reynolds \r\n\r\nEdition: 2nd Edition \r\n\r\nTopics: The Complete E-Commerce Book offers a wealth of information on how to design, build and maintain a successful web-based business.... Many of the chapters are filled with advice and information on how to incorporate current e-business principles\r\n', 'MDEC20', 'image14.jpg', '2012-08-27', 'false', 0);
INSERT INTO `books` VALUES(43, 'MDEC005', 'Design and Launch an E-Commerce Business in a Week (ClickStart Series)', 35, 'Author: Jason Rich\r\n\r\nEdition: 3rd Edition \r\n\r\nTopics: In just days, you can build your own eCommerce website, reach potential customers by the millions, process orders 24/7 and accept payments from all over the world—with no technical background or graphic design skills!\r\n', 'MDEC20', 'image15.jpg', '2012-08-20', 'false', 0);
INSERT INTO `books` VALUES(44, 'MDCS001', 'Corporate Computer Security', 30, 'Author: Randall J. Boyle\r\n\r\nEdition: 3rd Edition \r\n\r\nTopics: A strong business focus through a solid technical presentation of security tools. Boyle/Panko provides a strong business focus along with a solid technical understanding of security tools. This text gives readers the IT security skills they need for the workplace. This edition is more business focused and contains additional hands-on projects, coverage of wireless and data security, and case studies.', 'MDCS10', 'image1.jpg', '2012-08-10', 'false', 0);
INSERT INTO `books` VALUES(45, 'MDCS002', 'Computer Security: Art and Science', 29, 'Author: Matt Bishop\r\n\r\nEdition: 5th Edition \r\n\r\nTopics: This book provides a thorough and comprehensive introduction to computer security. It covers both the theoretical foundations and practical aspects of secure systems.', 'MDCS10', 'image2.jpg', '2012-08-01', 'false', 0);
INSERT INTO `books` VALUES(46, 'MDCS003', 'Introduction to Computer Security ', 10, 'Author: Ralph Argiento\r\n\r\nEdition: 3rd Edition \r\n\r\nTopics: Introduction to Computer Security is a teaching and learning tool that was designed for use in a classroom setting, encouraging students to learn by using these new technologies hands-on.\r\n', 'MDCS10', 'image3.jpg', '2012-10-22', 'false', 0);
INSERT INTO `books` VALUES(47, 'MDCS004', 'A basic Introduction to Computer Security ', 17, 'Author: Addison Wesley \r\n\r\nEdition: 3rd Edition \r\n\r\nTopics:  Introduction to Computer Security, 1e does NOT focus on the mathematical and computational foundations of security, and it does not assume an extensive background in computer science. Instead it looks at the systems, technology, management, and policy side of security, and offers students fundamental security concepts and a working knowledge of threats and countermeasures with “just-enough” background in computer science. The result is a presentation of the material that is accessible to students of all levels.', 'MDCS10', 'image4.jpg', '2012-07-22', 'false', 0);
INSERT INTO `books` VALUES(48, 'MDCS005 ', 'Principles of Computer Security CompTIA Security + and Beyond', 21, 'Author: Gregory White\r\n\r\nEdition: 2nd Edition \r\n\r\nTopics: This up-to-date, full-color guide discusses communication, infrastructure, operational security, attack prevention, disaster recovery, computer forensics, and much more.\r\n', 'MDCS10', 'image5.jpg', '2012-10-22', 'false', 0);

1 个答案:

答案 0 :(得分:2)

在PHP中,print_r用于调试,并打印有关变量的人类可读信息。您想使用print