JSONObject类参数问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JSONObject类参数问题相关的知识,希望对你有一定的参考价值。
JSONObject json = new JSONObject(这里根据提示只能写布尔值);
re是String类型。
我为什么写不进去String的变量,已经导包了。
org.json.JSONObject json = org.json.JSONObject.fromObject("\"name\":\"json\",\"bool\":true,\"int\":1");
String jname = json.getString("name");
boolean jbool = json.getInt("bool");
int jint=json.getString("int");
System.out.println(jname);
System.out.println(jbool);
System.out.println(jint);
用的解析器是 net\\sf\\json-lib\\json-lib\\2.4\\json-lib-2.4-jdk15.jar 和相关的依赖 参考技术A 提示参数只能是boolean,你传string肯定有问题啊 参考技术B 如果你用的是net.sf.json.JSONObject类,有无参数的构造方法,可以写成
JSONObject jobj = new JSONObject();
或者
JSONObject json = JSONObject.fromObject("\"name\":\"json\",\"bool\":true,\"int\":1");追问
JSONObject json = JSONObject.fromObject("\"name\":\"json\",\"bool\":true,\"int\":1");
JSONObject response = json.getJSONObject("json");
JSONArray data = response.getJSONArray("json");
JSONObject info = data.getJSONObject(0);
String name=info.getString("name");
System.out.println(name);
我用的这个JSONObject.fromObject,可以传入字符串类型,但这样输出好像不对,能教我下怎么解析并输出吗。
无法使用类型为“的参数列表”调用“jsonObject”(带有:NSData,选项:JSONSerialization.ReadingOptions,错误:inout NSError?)
【中文标题】无法使用类型为“的参数列表”调用“jsonObject”(带有:NSData,选项:JSONSerialization.ReadingOptions,错误:inout NSError?)【英文标题】:Cannot invoke 'jsonObject' with an argument list of type '(with: NSData, options: JSONSerialization.ReadingOptions, error: inout NSError?) 【发布时间】:2016-12-05 03:47:03 【问题描述】:我是 iOS 的新手开发者,仍在学习 youtube 或阅读一些有关 swift 的电子书等。
实际上,我在 youtube iOS Login and Signup Screen Tutorial 上关注了有关如何使用 JSON 数据创建 iOS 登录和注册的本教程,但我认为该代码在带有 xcode 8 的 swift 3 中效果不佳。我有一些问题/错误,我现在不能解决这个问题,我已经google了,但我不知道如何解决这个问题。
这是我的 LoginVC.swift 文件中的屏幕截图
Screenshot of error on my LoginVC.swift
这是 LoginVC.swift 中的所有代码
import UIKit
class LoginVC: UIViewController
@IBOutlet weak var txtUsername: UITextField!
@IBOutlet weak var txtPassword: UITextField!
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view.
override func didReceiveMemoryWarning()
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
@IBAction func btnLoginTapped(_ sender: UIButton)
// let userName = txtUsername.text;
// let userPassword = txtPassword.text;
let username = txtUsername.text
let password = txtPassword.text
if ( username!.isEqual("") || password!.isEqual("") )
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Please enter Username and Password"
alertView.delegate = self
alertView.addButton(withTitle: "OK")
alertView.show()
else
var post:NSString = "username=\(username)&password=\(password)" as NSString
NSLog("PostData: %@",post);
var url:NSURL = NSURL(string:"http://192.168.1.17/userAPI/api/users")!
var postData:NSData = post.data(using: String.Encoding.ascii.rawValue)! as NSData
var postLength:NSString = String( postData.length ) as NSString
var request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.httpBody = postData as Data
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: URLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &reponseError)
if ( urlData != nil )
let res = response as! HTTPURLResponse!;
// let dict: [String: Any] = ["key": value]
NSLog("Response code: %ld", res?.statusCode ?? <#default value#>);
if ((res?.statusCode)! >= 200 && (res?.statusCode)! < 300)
var responseData:NSString = NSString(data:urlData! as Data, encoding:String.Encoding.utf8.rawValue)!
NSLog("Response ==> %@", responseData);
var error: NSError?
let jsonData:NSDictionary = JSONSerialization.jsonObject(with: urlData!, options: JSONSerialization.ReadingOptions.mutableContainers, error: &error) as! NSDictionary
// let jsonData:NSDictionary = JSONSerialization.JSONObjectWithData(urlData!, options:JSONSerialization.ReadingOptions.MutableContainers , error: &error) as! NSDictionary
let success:NSInteger = jsonData.value(forKey: "success") as! NSInteger
//[jsonData[@"success"] integerValue];
NSLog("Success: %ld", success);
if(success == 1)
NSLog("Login SUCCESS");
var prefs:UserDefaults = UserDefaults.standard
prefs.set(username, forKey: "USERNAME")
prefs.set(1, forKey: "ISLOGGEDIN")
prefs.synchronize()
self.dismiss(animated: true, completion: nil)
else
var error_msg:NSString
if jsonData["error_message"] as? NSString != nil
error_msg = jsonData["error_message"] as! NSString
else
error_msg = "Unknown Error"
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = error_msg as String
alertView.delegate = self
alertView.addButton(withTitle: "OK")
alertView.show()
else
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failed"
alertView.delegate = self
alertView.addButton(withTitle: "OK")
alertView.show()
else
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign in Failed!"
alertView.message = "Connection Failure"
if let error = reponseError
alertView.message = (error.localizedDescription)
alertView.delegate = self
alertView.addButton(withTitle: "OK")
alertView.show()
func textFieldShouldReturn(textField: UITextField) -> Bool
//delegate method
textField.resignFirstResponder()
return true
错误实际上在以下几行:
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &reponseError)
NSLog("Response code: %ld", res?.statusCode ?? <#default value#>);
let jsonData:NSDictionary = JSONSerialization.jsonObject(with: urlData!, options: JSONSerialization.ReadingOptions.mutableContainers, error: &error) as! NSDictionary
我有点卡住并困惑如何解决这个问题。
有人来帮忙解决这个问题吗?对此,我真的非常感激。或者有人可以告诉我如何在 Swift3 中使用 API 学习和创建登录屏幕?
谢谢你的帮助,祝大家今天有好事发生!
【问题讨论】:
是的,iOS 在 swift 3 中改变了很多语法。只需检查 XCode 显示错误的方法。 Swift 更改语法。将该方法更改为最新的语法类 func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any @New16 谢谢你这么快回复我,呵呵..是的,错误在截图上,实际上我构建项目后有3个错误。 @GeneCode 好的,先生,我会尝试更改,谢谢您的帮助。 :) 【参考方案1】:这是因为我们在获取数据时没有处理错误。所以我们需要安全地键入种姓数据,然后将其传递给 JsonSerializer。这是代码。
do
let data = try NSData.init(contentsOfFile: path) as Data
let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
print(jsonArray)
catch
【讨论】:
以上是关于JSONObject类参数问题的主要内容,如果未能解决你的问题,请参考以下文章
JSONSerialization.jsonObject 不接受我的参数
如何使用 ResponseEntity 返回 JSONObject 而不是 HashMap? (未找到类型返回值的转换器:类 org.json.JSONObject)