使用 pojo 从纯字符串创建 JSON
Create JSON from a plain string using pojo
我在 java 中有一个纯字符串,如下所示
Roll: 1
Name: john
Roll: 2
Name: jack
Roll: 3
Roll: 4
Name: julie
请参阅此处以了解缺少第 3 卷名称,
我想将上面的字符串转换为 json,如下所示,
{ "block":[ { "Roll":"1", "Name":"john" }, { "Roll":"2", "Name":"jack" }, { "Roll":"4", "Name":"julie" } ] }
如何使用 java、gson 和 pojo 实现它。
这是我的建议:
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
public class Test {
public static void main(String[] args) {
Gson gson = new Gson();
String s = "Roll: 1\nName: john\nRoll: 2\nName: jack\nRoll: 3\nRoll: 4\nName: julie";
String[] values = s.split("\n");
List<Obj> objects = new ArrayList<Obj>();
for(int i = 0; i < values.length - 1; i++){
Obj o = new Obj(0, null);
if(values[i].startsWith("Roll")){
o.Roll = Integer.parseInt(values[i].split(":")[1].trim());
if(values[i + 1].startsWith("Name")){
o.Name = values[i + 1].split(":")[1];
i++;
} else {
o.Name = null;
}
}
objects.add(o);
}
EndResult result = new EndResult();
result.block = new Obj[objects.size()];
for(int i = 0; i < objects.size(); i++){
result.block[i] = objects.get(i);
}
System.out.println(gson.toJson(result));
}
}
class EndResult{
Obj[] block;
}
class Obj{
int Roll;
String Name;
Obj(int Roll, String Name){
this.Roll = Roll;
this.Name = Name;
}
}
我在 java 中有一个纯字符串,如下所示
Roll: 1
Name: john
Roll: 2
Name: jack
Roll: 3
Roll: 4
Name: julie
请参阅此处以了解缺少第 3 卷名称,
我想将上面的字符串转换为 json,如下所示,
{ "block":[ { "Roll":"1", "Name":"john" }, { "Roll":"2", "Name":"jack" }, { "Roll":"4", "Name":"julie" } ] }
如何使用 java、gson 和 pojo 实现它。
这是我的建议:
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
public class Test {
public static void main(String[] args) {
Gson gson = new Gson();
String s = "Roll: 1\nName: john\nRoll: 2\nName: jack\nRoll: 3\nRoll: 4\nName: julie";
String[] values = s.split("\n");
List<Obj> objects = new ArrayList<Obj>();
for(int i = 0; i < values.length - 1; i++){
Obj o = new Obj(0, null);
if(values[i].startsWith("Roll")){
o.Roll = Integer.parseInt(values[i].split(":")[1].trim());
if(values[i + 1].startsWith("Name")){
o.Name = values[i + 1].split(":")[1];
i++;
} else {
o.Name = null;
}
}
objects.add(o);
}
EndResult result = new EndResult();
result.block = new Obj[objects.size()];
for(int i = 0; i < objects.size(); i++){
result.block[i] = objects.get(i);
}
System.out.println(gson.toJson(result));
}
}
class EndResult{
Obj[] block;
}
class Obj{
int Roll;
String Name;
Obj(int Roll, String Name){
this.Roll = Roll;
this.Name = Name;
}
}