将无效的Json转换为有效的json android? [英] Convert Invalid Json into valid json android?

查看:149
本文介绍了将无效的Json转换为有效的json android?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将jnvalid JSON数据转换为有效的JSON数据。我在下面有这样的JSON。是否有任何使用Java更改它的逻辑?

I want to convert jnvalid JSON data into valid JSON data. I have JSON like this below. Is there any logic to change it using Java?

 {
    name: date,
    order: 1,
    required: true,
    type: date,
    placeholder: Expense Date
}

I想要有效的JSON数据格式如下:

I want valid JSON data formatted as below:

{
    "name": "date",
    "order": "1",
    "required": "true",
    "type": "date",
    "placeholder": "Expense Date"
 }


推荐答案

我不打算为你做这个没有为你所做的事情提供任何代码,但我将指导你如何做到这一点。
逐行迭代文件或字符串。
然后实例化一个字符串构建器以继续附加有效的JSON。
将第一个引号附加到字符串构建器,然后在一行上使用line.split(':')来获取具有行的前半部分和后半部分的数组。然后将splitLine [0](上半部分)附加到字符串构建器上,追加冒号,附加行splitLine [1]的后半部分,最后附加最后一个引号和逗号。现在为每一行执行此操作,您将获得有效的JSON。

I'm not going to do it for you as you haven't provided any code to what you have done but I will guide you on how to do it. Iterate over the file or the string whatever you have it on, line by line. Then instantiate a string builder to keep appending the valid JSON to. append the first quote to the string builder, then use line.split(':') on a single line to get an array with the 1st half of the line and the second half. Then append the splitLine[0] (1st half) onto the string builder, append the colon, append the 2nd half of the line splitLine[1] and finally append the last quote and the comma. Now do this for every line and you will have valid JSON.

这是我上面解释的工作版本。

Here is a working version of what I explained above.

String inputString = "name: date, order: 1, required: true, type: date, placeholder: Expense Date";
StringBuilder validJson = new StringBuilder();
validJson.append("{");
String[] lineByLine =  inputString.split(",");
for(int i =0; i< lineByLine.length; i++){
    String[] lineSplit = lineByLine[i].split(":");
    validJson.append('"').append(lineSplit[0].trim()).append('"').append(":").append('"').append(lineSplit[1].trim()).append('"').append(i==lineByLine.length-1?"}":",");
}
String finishedJSON = validJson.toString();
System.out.println(finishedJSON);

最后的位可能看起来有些混乱

The bit at the end may look a little confusing

i==lineByLine.length-1?"}":","

但它正在做的是检查它是否是JSON的最后一行用括号关闭它,否则为下一个属性准备一个逗号

But what it is doing is checking if it's the last line of JSON close it with a bracket, otherwise place a comma ready for the next attribute

这篇关于将无效的Json转换为有效的json android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆