简体   繁体   English

java - javax.json - 如何检查值是否为字符串

[英]java - javax.json - How to check if a value is a string

I have a database I made in Json.我有一个用 Json 制作的数据库。 I have this parsed, and have the code iterating through a Json array, which contains several Json objects.我对此进行了解析,并让代码遍历一个包含多个 Json 对象的 Json 数组。 Finally, I also am iterating through the values in the Json objects.最后,我还遍历 Json 对象中的值。 My problem is that I need to check if the value that the iterator is on, is a string or an array.我的问题是我需要检查迭代器所在的值是字符串还是数组。

Google seems to only have things like checking if there is a number in a string, or some other variation of that question.谷歌似乎只有检查字符串中是否有数字或该问题的其他变体之类的东西。

SO questions doesn't appear to have much for what I want.所以问题似乎对我想要的东西没有多少。 There was a case that was very similar to mine, however it is dealing with primitive data types, so my case that is dealing with string doesn't work.有一个案例与我的非常相似,但是它处理的是原始数据类型,所以我处理字符串的案例不起作用。 (Here is the link to that other case: Java how to check if a string value is a type of given Class<?> ) (这是另一个案例的链接: Java how to check if a string value is a type of given Class<?>

Here is a small portion of my database: The configuration arrays get longer as you go deeper into the database.这是我的数据库的一小部分:随着您深入数据库,配置数组变得更长。 I can not simply hold the values in a string, as "superscript" needs to be formatted as a superscript on the "term".我不能简单地将值保存在字符串中,因为“上标”需要格式化为“术语”的上标。 I plan to do this later, but either way I will need to have the program figure out if it is dealing with a string or an array.我打算稍后再做,但无论哪种方式,我都需要让程序弄清楚它是在处理字符串还是数组。

{
"Elements" : [
    {
    "name" : "Hydrogen",
    "Symbol" : "H",
    "atomicNumber" : "1",
    "electronegativity" : "2.2",
    "group" : "Hydrogen",
    "ionCharge1" : "1+",
    "ionCharge2" : "1-",
    "molarMass" : "1.01",
    "naturalState" : "Gas",
    "synthetic" : "false",
    "diatomic" : "true",
    "columnNumber" : "1",
    "row" : "1",
    "columnCode" : "IA",

    "nobleGasConfiguration" : [
        {
        "term:" : "No Noble Gas Configuration",
        "superScript" : "-"
        }
    ],
    "electronConfiguration" : [
        {
        "term" : "1s",
        "superScript" : "1"
        }
    ]
    }
}

Here is my code: The part of the code that is post to find out whether it is dealing with a string or a array is at the if statement (there is only 1 if statement)这是我的代码:用于确定它是处理字符串还是数组的代码部分位于 if 语句中(只有 1 个 if 语句)

import javax.json.Json;
import javax.json.JsonReader;
import javax.json.JsonStructure;
import javax.json.JsonObject;
import javax.json.JsonArray;
import javax.json.JsonValue;
import java.util.Iterator;
import java.util.Collection;
import java.io.FileReader;
import java.io.IOException;
import java.lang.String;

public class DataTest
{
public static void main(String[]args) throws IOException
{
    String strValue = "";
    JsonReader reader = Json.createReader(new FileReader("Elements.JSON"));
    JsonObject jsonst = reader.readObject();

    JsonArray elements = jsonst.getJsonArray("Elements"); 
    for (int i = 0; i < elements.size(); i++) 
    {
        JsonObject element = elements.getJsonObject(i); 
        Collection<String> elementValues = element.keySet(); 
        Iterator<String> elementKeys = elementValues.iterator(); 
        while(elementKeys.hasNext())
        {
            if(elementKeys.next() instanceof java.lang.String)
            {
                System.out.println(elementKeys.next());
                String elementKey = elementKeys.next();
                strValue = element.getString(elementKey); 
                System.out.println(strValue); 
            }
        }
    }

    reader.close();
}
}

I think I have the if statement is almost completed, but I have into the original problem again.我想我的if语句已经快完成了,但是我又陷入了原来的问题。 elementKeys.next() gets the name for a value. elementKeys.next() 获取值的名称。 For example "name", "symbol", "nobleGasConfiguration".例如“名称”、“符号”、“nobleGasConfiguration”。 For the actual values (like "Hydrogen" from "name" : "Hydrogen"), I've been getting that as a string with the .getString() method.对于实际值(如 "name" 中的 "Hydrogen" : "Hydrogen"),我已经使用 .getString() 方法将其作为字符串获取。 However, this causes the program to crash when it tries to get a array, because .getString() is for getting strings... Not arrays.但是,这会导致程序在尝试获取数组时崩溃,因为 .getString() 用于获取字符串...不是数组。

My main issue is getting the correct value to check.我的主要问题是获取正确的值进行检查。 My current if statement always comes up as true.我当前的 if 语句总是正确的。 This is because the values that .next() gets are indeed strings, and therefore the instanceof returns true.这是因为 .next() 获取的值确实是字符串,因此 instanceof 返回 true。 This the case even for the array names.即使对于数组名称也是如此。 Then the program goes into the if statement and crashes when .getString() tries to get an array.然后程序进入 if 语句并在 .getString() 尝试获取数组时崩溃。

if(elementKeys.next() instanceof java.lang.String)

So, my question.所以,我的问题。 How do I safely get the right value (such as "Hydrogen" from "name" : "Hydrogen") for my if statement to check?我如何安全地为我的 if 语句检查正确的值(例如“名称”中的“氢”:“氢”)? (Doesn't matter if I need to use an entirely different method to check the value type, ultimately I need a means to check the value type) (如果我需要使用完全不同的方法来检查值类型并不重要,最终我需要一种检查值类型的方法)

What programs/versions am I using?我使用的是什么程序/版本?

Notepad记事本

Command-prompt命令提示符

Java 8爪哇 8

javax.json-1.0.jar javax.json-1.0.jar

Please keep the answers to java and javax.json.请保留 java 和 javax.json 的答案。

I have modified your class to process nested JsonArray type elements recursively, effectively flattening out the properties.我已经修改了您的类以递归处理嵌套的 JsonArray 类型元素,从而有效地使属性变平。 You should be able to make slight modifications to this code as a basis to accomplish what you wish.您应该能够对此代码进行轻微修改,以此作为实现您希望的基础。 Good luck.祝你好运。

import javax.json.*;
import java.io.FileReader;
import java.util.List;
import java.util.Set;

public class DataTest {
    public void processJson(String path) {
        JsonReader reader = null;
        try {
            reader = Json.createReader(new FileReader(path));
            JsonObject jsonObj = reader.readObject();
            processJsonObject(jsonObj);
        } catch (Exception ioe) {
            ioe.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }

    private void processJsonObject(JsonObject jsonObj) {
        Set<String> keys = jsonObj.keySet();
        for (String key : keys) {
            JsonValue value = jsonObj.get(key);
            processJsonObject(key, value);
        }
    }

    private void processJsonObject(String key, JsonValue value){
       switch(value.getValueType()){
           case ARRAY:
               processJsonObject(key, (JsonArray)value);
               break;
           default:
               processJsonObject(key, (JsonString)value);
       }
    }

    private void processJsonObject(String key, JsonArray array) {
        System.out.println("Array:  key[" + key + "] = " + "An Array: " + array);
        List<JsonObject> elements = array.getValuesAs(JsonObject.class);
        for(JsonObject element: elements) {
            processJsonObject(element);
        }
    }

    private void processJsonObject(String key, JsonString value) {
        System.out.println("String: key[" + key + "] = " + value);
    }

    public static void main(String[] args) {
        DataTest test = new DataTest();
        test.processJson("/Data/Test/src/main/resources/elements.json");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM