从文件(不是JSON)读取数据并转换为对象

时间:2019-04-22 00:20:32

标签: swift

我正在尝试从文件的内容读取并转换为对象。内容是字典数组,但不是JSON(键不包含在引号中)。 内容如下

public void start() throws Exception {
    startTime = System.nanoTime();
    for (Riddle riddle: riddles) {
        boolean cond = false;
        while (cond != true) {
            String useranswer = this.promptRiddle(riddle);
            boolean keepGoing = checkAnswer(riddle, useranswer);
            if (keepGoing = true) {
                cond = true;
            } else {
                cond = false;
            }
        }
    }
    endTime = System.nanoTime();

}
public String promptRiddle(Riddle thisriddle) {
    System.out.println(thisriddle.getRiddle());
    System.out.println("Answer: ");
    guess = keyboard.next().replaceAll("[^a-zA-Z0-9]+", "").toLowerCase();
    return guess;
}

public String getUserInput() {
    System.out.println("What level of difficulty do you want to play? Enter: easy, medium or hard");
    userInput = keyboard.nextLine();
    if (userInput.equals("easy")) {
        level = "easy";
    } else if (userInput.equals("medium")) {
        level = "medium";
    } else if (userInput.equals("hard")) {
        level = "hard";
    }
    return level;
}
public boolean checkAnswer(Riddle theRiddle, String guess) {
    boolean yuh = false;

    correct = theRiddle.getAnswer();

    System.err.println("You guessed: " + guess + ", and Answer was: " + correct);
    if (guess.equals(correct)) {
        System.out.println("Congrats! You got it.");
        p1.win();
        yuh = true;
        keepGoing = true;
    } else {
        p1.wrong();
        String userInputHint;
        System.out.println("YOU WANT A HINT?! enter: yes or no");
        keyboard.nextLine();
        userInputHint = keyboard.nextLine();
        yuh = false;
        if (userInputHint.equals("yes")) {
            System.out.println("HINT:" + theRiddle.getHint());
        } else {}
    }
    return yuh;
}
public long calculateTime() {
    totalTime = (endTime - startTime) / 1000000000;
    return totalTime;
}

public class Person {
    public int score = 0;
    BuildGame totalTime;

    public Person() {
        score = 0;
    }
    public void win() {
        score++;
    }
    public void wrong() {
        score--;
    }
    public String toString() {
        String s;
        s = "Player's score: " + score + " and Player's time is  " + totalTime + " seconds";
        return s;
    }

我希望能够读取它并制作一个结构如下的对象数组:

[ {
    id: 13,
    start: "2018-01-12",
    end: "2018-02-16",
    name: "Fourth item with a super long name"
  },
  {
    id: 14,
    start: "2018-02-01",
    end: "2018-02-02",
    name: "Fifth item with a super long name"
  }
]

首选编码方式,但不是必需的。

我尝试过Google,但是没有运气。

2 个答案:

答案 0 :(得分:0)

我会将not-json字符串转换为json字符串:

let notjson = """
[
{
    id: 13,
    start: "2018-01-12",
    end: "2018-02-16",
    name: "Fourth item with a super long name"
},
{
    id: 14,
    start: "2018-02-01",
    end: "2018-02-02",
    name: "Fifth item with a super long name"
}
]
"""

let pattern = "(\n\\s*)([a-z]*)(:)"
let repl = "$1\"$2\"$3"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let json = regex.stringByReplacingMatches(in: notjson, options: [], 
    range: NSRange(location: 0, length: notjson.utf16.count), withTemplate: repl)

好的,所以现在我们将其简化为先前解决的问题,就像我们在数学中所说的那样。我们有json,所以我们可以解码它:

struct Thing : Decodable {
    let id : Int
    let start : String
    let end : String
    let name : String
}
let things = try! JSONDecoder().decode([Thing].self, from:json.data(using: .utf8)!)

答案 1 :(得分:0)

在上面的评论中,您询问是否存在将文本转换为JSON的方法,以便可以将Codable与之配合使用。

这是一种脆弱的方法。如果非JSON文件是与您的应用程序捆绑在一起的静态文件,那么这应该不是问题。如果要从某些Web服务获取此数据,请不要使用它。

将文件读入变量。 (在这里,我将手动进行说明。)

let string = """
[
    {
        id: 13,
        start: "2018-01-12",
        end: "2018-02-16",
        name: "Fourth item with a super long name"
    },
    {
        id: 14,
        start: "2018-02-01",
        end: "2018-02-02",
        name: "Fifth item with a super long name"
    }
]
"""

正则表达式替换空格,后跟单词和冒号(例如:id:),并用引号引起来。

let json = string.replacingOccurrences(of: "\\s+(\\w+): ", with: "\"$1\": ", options: [.regularExpression])

这将输出以下字符串:

[
    {
        "id": 13,
        "start": "2018-01-12",
        "end": "2018-02-16",
        "name": "Fourth item with a super long name"
    },
    {
        "id": 14,
        "start": "2018-02-01",
        "end": "2018-02-02",
        "name": "Fifth item with a super long name"
    }
]

然后您应该可以使用可编码的字符串将其解码为JSON。