我正在学习Java。我有一个示例日志文件,其中包含密钥对及其值。我想从某些行中找到一个密钥对及其价值。例如,如果行以“ x”开头,请读取该行并找到它。我能够获取密钥对及其在输出文件中的值,但无法获取行尾的json对象。目标是将文本文件作为输入,并查找句子是否以特定单词开头。如果是,请从该行中查找键对和值,并包含json对象(如果有)
任务:查找以“ [Student info]”开头的行,并解析学生ID,班级状态,输入(这是json对象)。有时输入也可能为空。
我已经在该平台上检查了其他问题,包括this,但并没有太大帮助。
**Input file.**
[King] 9 AM America -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: unknown Input={||Ouptut={}
[born time] 9 AM London -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: unknown Input={||Ouptut={}
[Student info] -- 12/08/2011 -- StudentId: 124421 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={ || Ouput={}
[born time] 9 AM London -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: unknown Input={||Ouptut={}
[Student info] -- 12/08/2011 -- StudentId: 1234567 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={
"kaju": [{
"Sno": {
"type": "literal",
"value": "random"
}
}]
}
[Game] 9 AM London -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: unknown Input={
[Student info] -- 12/08/2011 -- StudentId: 1234567 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={ || Ouput={
"core": [{
"id": {
"datatype": "https://www.w3schools.com/",
"type": "website",
"value": "study"
},
"entity": {
"type": "url",
"value": "https://www.w3schools.com/"
},
"Sno": {
"type": "literal",
"value": "random"
}
}]
}
**Expected Output File**
[Student info] -- 12/08/2011 -- StudentId: 124421 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={ || Ouput={}
[Student info] -- 12/08/2011 -- StudentId: 1234567 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={
"kaju": [{
"Sno": {
"type": "literal",
"value": "random"
}
}]
}
[Student info] -- 12/08/2011 -- StudentId: 1234567 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={ || Ouput={
"core": [{
"id": {
"datatype": "https://www.w3schools.com/",
"type": "website",
"value": "study"
},
"entity": {
"type": "url",
"value": "https://www.w3schools.com/"
},
"Sno": {
"type": "literal",
"value": "random"
}
}]
}
**Current Output File**
[Student info] -- 12/08/2011 -- StudentId: 124421 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={ || Ouput={}
[Student info] -- 12/08/2011 -- StudentId: 1234567 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={
[Student info] -- 12/08/2011 -- StudentId: 1234567 -- Phonenumber: 4252076406 -- ClassStatus: Senior -- "Random String..." Input={ || Ouput={
从上面的文本文件中您可以看到,我只能提取所需的行(学生信息),但无法获取附加的json对象。我也希望抽象json对象(如果有)。在这种情况下,新行始终以“ [”开头。
注意:
下面是我的代码。
public class Kickstarter {
public static void main (String... args) {
Scanner scan = new Scanner(Kickstarter.class.getResourceAsStream("sample.txt"));
List<String> fileByLine = new ArrayList<>();
List<StudentInfo> result = new ArrayList<>();
while(scan.hasNextLine()) {
fileByLine.add(scan.nextLine());
}
for (Iterator<String> iterator = fileByLine.iterator(); iterator.hasNext();) {
String line = iterator.next();
if (!line.startsWith("[Student info]")) {
iterator.remove();
}
}
for (int i = 0; i < fileByLine.size(); i++) {
System.out.println(fileByLine.get(i));
}
}
}
另一个文件
import com.google.gson.JsonObject;
public class StudentInfo {
public String studentinfo;
public boolean isBasic;
public JsonObject json;
public String jsonStringBuildUp;
public StudentInfo (String studentinfo, boolean isBasic) {
this.studentinfo = studentinfo;
this.isBasic = isBasic;
this.json = null;
this.jsonStringBuildUp = "";
}
}
答案 0 :(得分:0)
loadData
您需要创建如下的POJO类。
StudentInfo.java
<?php
$url = 'https://query1.finance.yahoo.com/v1/finance/screener?lang=en-US®ion=US&formatted=true&corsDomain=finance.yahoo.com';
// $url = 'https://finance.yahoo.com/screener/unsaved/f0171a68-053e-42f2-a941-d6ecdf2ba6d1';
$parameters =
[
'size' => 25,
'offset' => 50,
'sortField' => 'intradaymarketcap',
'sortType' => 'DESC',
'quoteType' => 'EQUITY',
'topOperator' => 'AND',
'query' => array(
'operator' => 'AND',
'operands'=> array(
'operator' => 'or',
'operands' => array(
'operator' => 'EQ',
'operands' => array("region","jp")
)
)
),
'userId' => 'HFEELK3VBE3KPE4MGEA6PZTXXL',
'userIdType' => 'guid'
];
$parameters = json_encode($parameters);
$headers =
[
'Accept: application/json, text/javascript, */*; q=0.01',
'Accept-Language: en-US,en;q=0.5',
'X-Requested-With: XMLHttpRequest',
'Connection: keep-alive',
'Pragma: no-cache',
'Cache-Control: no-cache',
];
$cookie = tmpfile();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.31');
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($parameters));
// curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
?>
Core.java
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import com.google.gson.Gson;
public class KickStarter {
private static final String STUDENT_INFO = "[Student info]";
private Map<String, StudentInfo> lineJsonMap;
private String key;
private StringBuilder jsonBuilder;
public static void main(String... args) {
new KickStarter().scan();
}
private void scan() {
Scanner scan = new Scanner(KickStarter.class.getClassLoader().getResourceAsStream("sample.txt"));
lineJsonMap = new HashMap<String, StudentInfo>();
jsonBuilder = null;
key = null;
while (scan.hasNextLine()) {
String line = scan.nextLine();
if (!line.startsWith("[")) {
if (jsonBuilder == null) {
jsonBuilder = new StringBuilder();
jsonBuilder.append("{");
}
jsonBuilder.append(line.trim());
} else if (line.startsWith(STUDENT_INFO)) {
extractJSON();
lineJsonMap.put(line, null);
key = line;
} else if (line.startsWith("[")) {
extractJSON();
}
}
extractJSON();
scan.close();
// Finally Print values
Set<Entry<String, StudentInfo>> entrySet = lineJsonMap.entrySet();
for (Entry<String, StudentInfo> entry : entrySet) {
System.out.println(entry.getKey());
StudentInfo value = entry.getValue();
if (value != null) {
Gson gson = new Gson();
System.out.println(gson.toJson(value));
}
}
}
private void extractJSON() {
if (key != null) {
StudentInfo fromJson = null;
if (jsonBuilder != null) {
Gson gson = new Gson();
fromJson = gson.fromJson(jsonBuilder.toString(), StudentInfo.class);
}
lineJsonMap.put(key, fromJson);
key = null;
jsonBuilder = null;
}
}
}
Id.java
public class StudentInfo {
private Core[] core;
private Kaju[] kaju;
public Core[] getCore() {
return core;
}
public void setCore(Core[] core) {
this.core = core;
}
@Override
public String toString() {
return "ClassPojo [core = " + core + "][kaju = " + kaju + "]";
}
public Kaju[] getKaju() {
return kaju;
}
public void setKaju(Kaju[] kaju) {
this.kaju = kaju;
}
}
Kaju.java
public class Core {
private Id id;
private Entity entity;
private Sno Sno;
public Id getId() {
return id;
}
public void setId(Id id) {
this.id = id;
}
public Entity getEntity() {
return entity;
}
public void setEntity(Entity entity) {
this.entity = entity;
}
public Sno getSno() {
return Sno;
}
public void setSno(Sno Sno) {
this.Sno = Sno;
}
@Override
public String toString() {
return "ClassPojo [id = " + id.toString() + ", entity = " + entity.toString() + ", Sno = " + Sno.toString() + "]";
}
}
Entity.java
public class Id {
private String value;
private String datatype;
private String type;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDatatype() {
return datatype;
}
public void setDatatype(String datatype) {
this.datatype = datatype;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "ClassPojo [value = " + value + ", datatype = " + datatype + ", type = " + type + "]";
}
}
Sno.java
public class Kaju {
private Sno Sno;
public Sno getSno() {
return Sno;
}
public void setSno(Sno Sno) {
this.Sno = Sno;
}
@Override
public String toString() {
return "ClassPojo [Sno = " + Sno + "]";
}
}