【问题标题】:JSON request body - objective c formattingJSON 请求正文 - 客观 c 格式
【发布时间】:2017-02-08 20:51:27
【问题描述】:

我有一个用 obj-c 编写的 iOS 应用程序,它接受在搜索框中输入的查询并在 elasticsearch api 上执行多匹配字段查询。有人可以帮助格式化 JSON 请求正文吗?这是我要格式化的 get 查询正文的示例:

GET /test/data/_search
{
  "min_score": 1.6,<br/>
  "query": { <br/>
      "multi_match": {<br/>
             "query": "smith",<br/>
             "fields": ["name", "surname"]<br/>
      }<br/>
    },<br/>
  "_source": ["name", "surname", "address"]<br/>
}<br/>

在我的代码中:

NSString *jsonRequest = [NSString stringWithFormat:@"{\"min_score\":\"1.6\",\"query\":{\"multi_match\":{\"name\",\"surname\":\"%@\"}},\"_source\":[\"name\",\"surname\",\"address\"]}",[self.searchTextField text]];

其中 [self.searchTextField text] 是从搜索字段中获取的值。

但是当我查询时从 ElasticSearch 返回时出现此错误:

reason = "意外字符 (',' (code 44)): 期待一个冒号 在 [Source:

处分隔字段名称和值\n

作为一个测试,使用查询来匹配一个字段可以正常工作,所以它看起来只是一个格式问题。

抱歉忘记添加这是我使用 JSON 正文设置发布的 URL 的位置:

[self postDataToUrl:@"http://localhost:9200/test/data/_search?pretty=true" withJson:jsonRequest];

然后传递给:

-(void)postDataToUrl:(NSString*)urlString withJson:(NSString*)jsonString
{
    NSData* responseData = nil;
    NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];

    responseData = [NSMutableData data] ;
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[data length]] forHTTPHeaderField:@"Content-Length"];

    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithRequest:request
                completionHandler:^(NSData *data,
                                    NSURLResponse *response,
                                    NSError *error) {
                    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    NSLog(@"the final output is:%@",responseString);
                    NSError *lerror = nil;
                    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0  error:&lerror];

                if (error != nil) {
                    NSLog(@"Error parsing JSON.");
                }
                else {

当我通过常规匹配主体时,这一切正常,例如:

NSString *jsonRequest = [NSString stringWithFormat:@"{\"min_score\":\"1.6\",\"query\":{\"match\":{\"name\":\"%@\"}},\"_source\":[\"name\",\"surname\",\"address\"]}",[self.searchTextField text]];

【问题讨论】:

  • 这应该是查询字符串吗?
  • 您的 json 无效。 “multi_match”字典中的“name”键没有值。您不应该在代码中手动创建 json 字符串,而是创建字典并使用 NSJSONSerialization 将其转换为有效的 json 字符串。
  • @MikeD 我添加了更多信息,希望能更清楚。
  • 我认为先将您的 jsonRequest 转换为字典,然后更新所需的键将更不容易出错,因为您创建一个 jsonString 然后通过格式化字符串来更新值

标签: ios objective-c json elasticsearch


【解决方案1】:

您可能需要检查搜索结果的内容。看起来你有一个回车\n,它在逗号之前破坏了字符串。您可以像这样删除回车:

NSString *newString = [[self.searchTextField text] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
NSString *jsonRequest = [NSString stringWithFormat:@"{\"min_score\":\"1.6\",\"query\":{\"match\":{\"name\":\"%@\"}},\"_source\":[\"name\",\"surname\",\"address\"]}", newString];

【讨论】:

    【解决方案2】:

    检查来自@cybergen 的帖子,JSON 正文设置不正确,Elastic 需要这种格式的 JSON 查询:

    {
      "query": {
        "multi_match" : {
          "query":    "smith", 
          "fields": [ "name", "surname" ] 
        }
      }
    }
    

    我格式化了 JSON 请求字符串以匹配我的代码中的内容。

    【讨论】:

      猜你喜欢
      • 2018-09-19
      • 2018-07-12
      • 2020-07-20
      • 2018-01-03
      • 1970-01-01
      • 2017-09-03
      • 2015-09-16
      • 2018-01-01
      • 1970-01-01
      相关资源
      最近更新 更多