我有这个字符串:
"type":"image","originX":"center","originY":"center","left":135,"top":259,"width":270,"height":519,"fill":"rgb(0,0,0)","overlayFill":null,"stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"src":"file:///C:/Users/Alvin%20Combrink/Dropbox/Entrepren%C3%B6rskap/Design/Hemsidan/Backgrunder/Labyrint.jpg","filters":[]},
每个部分都用逗号分隔,我希望能够将一些数字提取为双精度数。我想要的是left
,top
,scaleX
,scaleY
和angle
。我该如何解决这个问题?
感谢
答案 0 :(得分:2)
如果您不想依赖于使用JSON解析器(但是,如果您经常使用JSON,则应该使用JSON),可以对整个字符串使用split
- 方法并根据{进行拆分{1}}(逗号),找到您想要的数据块,根据,
拆分数据并直接从结果数组中的第二个插槽读取数据。
但是,您可能需要对最后一个:
进行子串,以便能够直接解析数字。
但就像我说的那样,如果你在程序中多次使用JSON,你真的想要使用某种类型的JSON解析器。
代码示例:
"
答案 1 :(得分:1)
我知道有人已经回复了,但我一直这样做,希望也有帮助:
public class HelloWorld{
public static void main(String []args){
String text ="\"type\":\"image\",\"originX\":\"center\",\"originY\":\"center\",\"left\":135,\"top\":259,\"width\":270,\"height\":519,\"fill\":\"rgb(0,0,0)\",\"overlayFill\":null,\"stroke\":null,\"strokeWidth\":1,\"strokeDashArray\":null,\"strokeLineCap\":\"butt\",\"strokeLineJoin\":\"miter\",\"strokeMiterLimit\":10,\"scaleX\":1,\"scaleY\":1,\"angle\":0,\"flipX\":false,\"flipY\":false,\"opacity\":1,\"shadow\":null,\"visible\":true,\"clipTo\":null,\"src\":\"file:///C:/Users/Alvin%20Combrink/Dropbox/Entrepren%C3%B6rskap/Design/Hemsidan/Backgrunder/Labyrint.jpg\"";
//Just left and scaleX for example
String left = readValue(text, "left");
String scaleX = readValue(text, "scaleX");
System.out.println("left:" + left);
System.out.println("scaleX:" + scaleX);
}
public static String readValue(String text, String key)
{
//search for the init of the value
int start = text.indexOf("\"" + key + "\"");
//search for the end of the value
int end = text.indexOf(",", start + key.length() + 3);
//return the value. these + 3 , is for quotes and ":"
return text.substring(start + key.length() + 3,end);
}
}