001/* 002 * Copyright 2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.revetsec.json; 018 019import com.revetsec.internal.json.JsonWriter; 020import org.jspecify.annotations.NonNull; 021import org.jspecify.annotations.Nullable; 022 023import javax.annotation.concurrent.Immutable; 024 025/** 026 * A JSON string. 027 * <p> 028 * Its value is well-formed UTF-16: an unpaired surrogate is rejected. It may hold any other character, including 029 * NUL and Unicode noncharacters, and it compares exactly, with no case folding or normalization. 030 * 031 * @author <a href="https://www.revetkn.com">Mark Allen</a> 032 * @since 1.0.0 033 */ 034@Immutable 035public final class JsonString implements JsonValue { 036 @NonNull 037 private final String value; 038 039 /** 040 * Returns a JSON string holding {@code value}. 041 * 042 * @param value the string's value 043 * @return the JSON string 044 * @throws NullPointerException if {@code value} is {@code null} 045 * @throws IllegalArgumentException if {@code value} contains an unpaired surrogate 046 * @since 1.0.0 047 */ 048 @NonNull 049 public static JsonString fromValue(@NonNull String value) { 050 return new JsonString(JsonInvariants.requireWellFormed(value)); 051 } 052 053 private JsonString(@NonNull String value) { 054 this.value = value; 055 } 056 057 /** 058 * Returns this string's value, which may be a secret or personal data. 059 * 060 * @return the value 061 * @since 1.0.0 062 */ 063 @NonNull 064 public String getValue() { 065 return this.value; 066 } 067 068 @Override 069 @NonNull 070 public String toJson() { 071 return JsonWriter.toJson(this); 072 } 073 074 @Override 075 public boolean equals(@Nullable Object other) { 076 return this == other || (other instanceof JsonString string && this.value.equals(string.value)); 077 } 078 079 @Override 080 public int hashCode() { 081 return this.value.hashCode(); 082 } 083 084 @Override 085 @NonNull 086 public String toString() { 087 return "JsonString{value=<redacted>}"; 088 } 089}