将JSONObject添加到JSONArray java

时间:2017-02-23 14:01:54

标签: java json

我需要将一个对象添加到JSONArray(其中已包含元素),因此我必须知道要添加的属性的类型,如果这是一个整数或字符串等,... 如何使用java将该对象添加到我的数组?

1 个答案:

答案 0 :(得分:0)

正如其他人所建议的那样,您只需在JsonArray构建器中使用add方法即可。

PortfolioHolding ph = new PortfolioHolding();
// fill ph

var anonymous = new
{
    fundIdentifier = ph.fundIdentifier,
    fundRating = ph.fundRating,
    fundExpenseRatio = ph.fundExpenseRatio,
    fundWeight = ph.fundWeight,
    fundAlpha = neededValue // here your value from ph or any other
};

var json = JsonConvert.SerializeObject(anonymous);

// deserialize

var deserializedAnonymous = JsonConvert.DeserializeAnonymousType(json, anonymous);

ph.fundExpenseRatio = deserializedAnonymous.fundExpenseRatio;
//other properties

这只是用于格式化JSON输出。

import javax.json.*;

public class JsonExample {
    public static void main(String[] args) {
        JsonObject personObject = Json.createObjectBuilder()
                .add("name", Json.createObjectBuilder()
                        .add("given", "John")
                        .add("middle", "Edward")
                        .add("surname", "Doe")
                        .build())
                .add("age", 42)
                .add("isMarried", true)
                .add("address", Json.createObjectBuilder()
                        .add("street", "Main Street")
                        .add("city", "New York")
                        .add("zipCode", "10044")
                        .add("country", "United States")
                        .build())
                .add("phoneNumber", Json.createArrayBuilder()
                        .add("+1 (718) 111-1111")
                        .add("+1 (718) 111-1112")
                        .build())
                .build();

        JsonArray personArray = Json.createArrayBuilder()
                .add(personObject) // Add person to array.
                .build();

        System.out.println(JsonUtil.prettyPrint(personArray));
    }
}

此示例使用以下依赖项:

import java.io.StringWriter;
import java.util.*;
import javax.json.*;
import javax.json.stream.JsonGenerator;

/* Based on: http://stackoverflow.com/a/32500882/1762224 */
public class JsonUtil {
    public static String prettyPrint(JsonStructure json) {
        return jsonFormat(json, JsonGenerator.PRETTY_PRINTING);
    }

    public static String jsonFormat(JsonStructure json, String... options) {
        StringWriter stringWriter = new StringWriter();
        Map<String, Boolean> config = buildConfig(options);
        JsonWriterFactory writerFactory = Json.createWriterFactory(config);
        JsonWriter jsonWriter = writerFactory.createWriter(stringWriter);

        jsonWriter.write(json);
        jsonWriter.close();

        return stringWriter.toString();
    }

    private static Map<String, Boolean> buildConfig(String... options) {
        Map<String, Boolean> config = new HashMap<String, Boolean>();

        if (options != null) {
            for (String option : options) {
                config.put(option, true);
            }
        }

        return config;
    }
}

这是输出:

apply plugin: 'java'

repositories {
    jcenter()
}

dependencies {
    compile 'javax.json:javax.json-api:1.1.0-M1'
    compile 'org.glassfish:javax.json:1.1.0-M1'
}